Using React Router part 1

React Router is a react package that enables you to use your url history to navigate and show different ‘pages’ on your browser. React router allows you to pass down props to these different pages as well which definitely comes in handy.

The first thing you have to do is install the package in your project’s directory using:

npm i react-router-dom

After installing, in your project at the index.js level, you want to:

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

You’ll also want to wrap your <App /> component in the <Router> tag.

Once you fire up your project’s server and it appears on your browser, go ahead and check your dev tools, components tab, and clock on Router. You’ll see that Router comes with its on methods that are available to use. They are “History”, “Location”, and “Match”. You can use these methods to set up different kinds of routes in your application.

Let’s pretend you have a Home page, an About page, and a Profile page. You are going to want to put your routes to these pages in your App.js file. There are three different ways to write a route and they behave somewhat differently.

The first, and easiest, way to write a route is to do it like so:

<Route path='/home'>

With this route, you cannot pass it any props. It will literally just execute and display your page.

The second way to write a route:

<Route path='/about' component={About}/>

To use this route, you have to import your ‘About’ page. You are able to use the react router methods with this second route, however, you won’t be able to pass it any of your own props.

The third and probably the most useful way to use a react route is to write it this way:

<Route 
exact
path='/'
render={(routerProps) => <Journal {...routerProps} />}
/>

The final way you can pass down your props into the routed component in the Route render function. You might want to use the ‘exact’ keyword here to make sure that the path has to be exact in order to render it. If you don’t use it, you’ll most likely end up displaying the page along with your other pages on the same page.

If you simply want to create a link tag, you can import { Link } from ‘react-router-dom’.

This is all for my part 1 of the my React Router series! I’ll go into more detail and show more examples of how the routes work in part number 2.