DEV Community

Cover image for Intro to React Router
Maasa Kono
Maasa Kono

Posted on

Intro to React Router

React has a routing library (React Router) which allows us to link to specific URLs, and then show or hide components depending on which URL is displayed. Here is a quick guide to dip your toes into using this handy tool.

Install React Router

To install the React Router, run the following in the terminal:

npm install react-router-dom

Use React Router

To start implementing routes in our app, we need to import BrowserRouter and Route from react-router-dom. Add the following line of code at the top of file where you will be using React Router:

import { BrowserRouter as Router, Route } from 'react-router-dom';

Note: It is common for BrowserRouter to be renamed as Router. The above line of code is how you would create an alias. Now, any time we see Router, it is referring to BrowserRouter.

Router is the base component for our application's routing, and we declare in here how React Router is used.

Nested within this component is the Route component, so it would look something like this:

ReactDOM.render((
  <Router>
    <Route path='/' component={Home} />
  </Router>),
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

You will notice that the Route component has two props (properties): path and component. What this line says is that when the URL matches the path ('/'), our app will render the specified component for Home.

Multiple Routes

More likely than not, we'll have multiple routes in our app. It is important to note that the Router component can only have one child element, so in order to work around this, all of the Route components can be placed within a <div> or <> tag, ending up looking like this:

ReactDOM.render((
  <Router>
    <div>
      <Route path='/' component={Home} />
      <Route exact path='/about' component={About} />
    </div>
  </Router>,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

As you can see, the Route for the About component uses exact path as opposed to just path. This is pretty self-explanatory, but we use this to ensure that the component renders only when the path matches the the whole path, and not just part of it. We may have an issue with our Home component rendering all the time, so in that case, we should make that an exact path as well.

Now, if you change your URL path to '/', then you should see the Home component, and when the path is changed to match '/about', the About component should be rendering!

This is really just the very tip of the iceberg. To delve deeper into React Router, check out this awesome site.

Top comments (0)