42
loading...
This website collects cookies to deliver better user experience
react-router-dom
to handle our routing, if you want to look at the documentation, you can refer to it herereact-router-dom
so run the following command in your terminal:npm install react-router-dom
//or
yarn add react-router-dom
import {BrowserRouter as Router, Route, Switch} from "react-router-dom"
import {BrowserRouter as Router, Route, Switch} from "react-router-dom"
function App() {
return (
<Router>
</Router>
)
}
import {BrowserRouter as Router, Route, Switch} from "react-router-dom"
function App() {
return (
<Router>
<Route path="/">
<Home/>
</Route>
<Route path="/about">
<About/>
</Route>
</Router>
)
}
Router
we will wrap all of our Routes
with the <Switch>
component like this:import {BrowserRouter as Router, Route, Switch} from "react-router-dom"
function App() {
return (
<Router>
<Switch>
<Route path="/">
<Home/>
</Route>
<Route path="/about">
<About/>
</Route>
</Switch>
</Router>
)
}
exact
key word to only allow the exact url to display our content:<Route exact path="/about">
<About/>
</Route>
import { NavLink } from 'react-router-dom'
const NavBar = () => {
return (
<div>
<NavLink to="/">Home</NavLink>
<NavLink to="/about">About</NavLink>
</div>
)
}
<Link>
and <NavLink>
is that when ever a Navlink route is selected the Navlink will have the link active attribute applied to it. Each Nav/Link component has to have the to
attribute to direct the user to the correct route. Notice that the value of the to
corresponds to our Routes in our App component.react-router-dom
. There are some really useful hooks like useHistory
, whicht you can use to redirect your user after an event, or `useParams to allow them follow a link for more details about something on your page. Definitely check out the documentation from React Router for more info.