In this post, I will show you how to include React Router in your react project.
It's easy to use and it's great for improving the navigation experience.ππ½
Here's a demo of a simple navbar (and the button in the About page that redirects back to Home):
Now let's see how to get started with React Router.
Installation
- Install react-router-dom
-
Note: Make sure that you're already working on a
create-react-app
before adding it to your project
npm install react-router-dom
Include the Router
- Wrap your
<App />
component with<BrowserRouter />
- Add each
<Route />
with its path and respective component - Wrap
<Switch />
around your routes. Switch will start looking for a matching route and theexact
attribute will make sure that it matches exactly what we want
The <Navbar />
component will take care of the <NavLink />
, more on this below.
import React from 'react';
import {BrowserRouter, Switch, Route} from 'react-router-dom';
import About from './About';
import Home from './Home';
import Navbar from './Navbar';
function App() {
return (
<BrowserRouter>
<Navbar />
<Switch>
<Route exact path="/" component={Home}/>
<Route exact path="/about" component={About}/>
</Switch>
</BrowserRouter>
);
}
export default App;
Add NavLink
-
<NavLink />
will act as each Navbar link, which is using client-side routing (exclusive of single-page applications) -
<NavLink />
comes with theactiveClassName
property, which will allow us to add CSS to active/non-active links
import React from 'react';
import {NavLink} from 'react-router-dom'
import './App.css';
export default function Navbar() {
return (
<div>
<NavLink
activeClassName="selected"
className="not-selected"
to="/"
exact
>HOME</NavLink>
<NavLink
to="/about"
activeClassName="selected"
className="not-selected"
exact
>ABOUT
</NavLink>
</div>
)
}
The useHistory
hook
- What does it do? It provides access to the history prop that you may use to navigate
- In other words,
useHistory
can be used for redirecting which is very convenient!
import React from 'react';
import {useHistory} from 'react-router-dom';
export default function About() {
const history = useHistory()
const handleClick = () => {
history.push('/')
}
return (
<div>
<h1>ABOUT</h1>
<p>THIS IS THE ABOUT PAGE</p>
<div>
<button
onClick={handleClick}>
Back to Home
</button>
</div>
</div>
)
}
And that's it! π¬
Top comments (4)
This is awesome. You have summarized all the basics of React Router in a concise manner. It would be great if you could also include URL Parameters nested routes also
An amazing piece. Coming from vue background and trying react, I'm keep this article for raining days you know.
Thanks Debi
Super clear, concise explanation of how to use React Router effectively! Nice work!
Lovely writeup Deborah! ππSo proud of you βΊοΈβΊοΈβΊοΈ