Routing React Apps — Getting started
React routes fit very nicely into any finished front-end application. You do not need much set up; react routes are friendly and easy to work with. When you finished creating all the components of your react app, you are able to add routes that render your different components. First run :
npm install --save react-router-dom
Add import { Link } from ‘react-router-dom’
to the component in which you will include your links. I want the links in my Navbar, so I imported the Link component to my Navbar component. Add <Link></Link>
around the elements/texts you would like to link to your routes. Add your routes in as<Link to='/home'>
. The to='/'
will be the route that appears in your URL. When you are finished creating your links, they should look like this:
To get your routes working, navigate to your top-level component and add import { BrowserRouter as Router, Route } from ‘react-router-dom’
to the top of the file (Adding as Router
is unnecessary, it just allows me to refer to the <BrowserRouter>
component simply as <Router>
). In your App component, add the <Router></Router>
wrapper:
My Navbar component will appear on every page and does not require any routes, so I leave it alone.
In your app, import any components that require routing. Each of these components will be wrapped in <Route></Route>
, and each <Route>
will appear as follows:
<Route path="/resume" component={ Resume } />
Make sure your <Link>
routes match your corresponding <Route>
paths.
When finished:
If you have a root path '/'
, you may need to use the property exact={true}
so the '/'
route finds the exact URL match.
And boom, you’ve got react routes!