DEV Community

loading...
Cover image for TIL - React Router

TIL - React Router

annequinkenstein profile image Anne Quinkenstein Updated on ・2 min read

SPA

'Classic' websites: different pages with different path, which are usually loaded entirely one by one from the server.

React: a Single-Page Applications (SPA):
In an SPA, an HTML document is loaded only when the application is opened, and will remain the same for the lifetime. The HTML document is "empty", in the <body> it just includes a <script> tags which loads the application, along with one empty tag, intended to contain the DOM generated by the application. The content of each visited page is entirely built inside the browser via React.

Therefore a navigation System is not coming natural. We use React Router to determine what to display. This way we can

  • display a custom url in the browser
  • allow the user to use the bookmarks
  • allow the user to use of the previous/next browser buttons

1. Install React Router.

2. Wrap the parent component (index.js) with a <BrowserRouter />.

import { BrowserRouter } from 'react-router-dom';
   <BrowserRouter>
       <App />
   </BrowserRouter>
Enter fullscreen mode Exit fullscreen mode

3. Create different Routes in the main <App> component.

import { Switch, Route } from 'react-router-dom';
<Switch>
   <Route exact path='/' component={Home} />
   <Route path='/users' component={Users} />
   <Route path='/contact' component={Contact} />
</Switch>
Enter fullscreen mode Exit fullscreen mode

Routing refers to establishing a correspondence between the current path (e.g. /users) and a component to be displayed (e.g. Users).
Only one of the Routes enclosed in a Switch can be active at a given time.

4. Navigate between components use <Link>

import { Link } from 'react-router-dom';
<ul className='Header'>
   <li><Link to='/'>Home</Link></li>
   <li><Link to='/users'>Users</Link></li>
   <li><Link to='/contact'>Contact</Link></li>
</ul>
Enter fullscreen mode Exit fullscreen mode

In the DOM the <Link to="..."> produces <a href="..."> elements as their output.

Navlinks

  • target the active Link with <Navlink>

import { NavLink } from 'react-router-dom';

<ul className='Header'>
   <li>
       <NavLink activeClassName='active' exact to='/'>Home</NavLink>
   </li>
   <li>
       <NavLink activeClassName='active' to='/users'>Users</NavLink>
   </li>
   <li>
       <NavLink activeClassName='active' to='/contact'>Contact</NavLink>
   </li>
</ul>
Enter fullscreen mode Exit fullscreen mode

Router in depth

Render Props

<Route path="/contact"
       render={ props => (
              <Contact tabs= {"valuePassed"} {...props}  />  
        )}
 />
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide