
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
Enter fullscreen mode Exit fullscreen mode
Include the Router
- Wrap your
component with
- Add each
with its path and respective component
- Wrap
around your routes. Switch will start looking for a matching route and the
exact
attribute will make sure that it matches exactly what we want
The component will take care of the
, 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 (
);
}
export default App;
Enter fullscreen mode Exit fullscreen mode
Add NavLink
-
will act as each Navbar link, which is using client-side routing (exclusive of single-page applications)
-
comes with the
activeClassName
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 (
HOME
ABOUT
)
}
Enter fullscreen mode Exit fullscreen mode
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 (
ABOUT
THIS IS THE ABOUT PAGE
Back to Home
)
}
Enter fullscreen mode Exit fullscreen mode
And that’s it!
from Tumblr https://generouspiratequeen.tumblr.com/post/633694088460435456