- This cheatsheet is based on React Router Dom
v6.7.0
- If you use a different version, some things may be different
-
Install:
npm install react-router-dom
-
Configure
<BrowserRouter>
:-
This is a root component so that you can use other functionality from React Router.
-
Usually you want to add
<BrowserRouter>
around your App component. -
For example, if you're using "Vite", you can add it in
main.jsx
://... import { BrowserRouter } from 'react-router-dom'; //... ReactDOM.createRoot(document.getElementById('root')).render( <React.StrictMode> <BrowserRouter> <App /> </BrowserRouter> </React.StrictMode>, )
- Note: in some places (documentation, labs, etc), you may see that imported with an alias. For example:
//... import { BrowserRouter as Router } from 'react-router-dom'; //... <Router> <App /> </Router>
- Note: in some places (documentation, labs, etc), you may see that imported with an alias. For example:
-
Example:
- You can find an example here
Steps:
-
Create your routes using the components
Routes
andRoute
://... import { Routes, Route } from "react-router-dom"; //... function App() { return ( <div className="App"> {/* ... */} <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> <Route path="*" element={<ErrorPage />} /> </Routes> {/* ... */} </div> ); } export default App;
-
Add a navigation menu, so that users can go to those routes.
Do not use<a>
tags (they will lead to a page reload).
Instead, we can use the components<Link>
or<NavLink>
://... import { Routes, Route, Link, NavLink } from "react-router-dom"; //... export default function App() { return ( <div className="App"> <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> <Link to="/contact">Contact</Link> </nav> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> <Route path="*" element={<ErrorPage />} /> </Routes> {/* ... */} </div> ); }
Notes:
-
In the prop
element
, you can pass any valid JSX. For example:<Route path="/contact" element={<div><h1>title</h1><h2>Subtitle</h2></div>} />
-
You can also pass properties. Ex:
<Route path="/menu" element={<Menu pizzas={pizzasArr} msg="i love pizza" />} />
-
Anything that you put outside the component
<Routes>
, will be rendered for all pages (for example, if you want to display the header or a footer in all pages).
Example:
- You can find an example here
How:
-
Instead of
<Link>
, you can also use<NavLink>
(it adds the class "active" to the html link when the user is navigating on a specific page).<nav> <NavLink to="/">Home</NavLink> <NavLink to="/about">About</NavLink> <NavLink to="/contact">Contact</NavLink> </nav>
-
You will also need to add some CSS. For example:
.nav a { color: blue; } .nav a.active { color: orange; }
Example:
- You can find an example here
Steps:
-
Define a dynamic route, using the following syntax:
<Routes> ... <Route path="/users/:userId" element={<UserDetails />} /> ... </Routes>
-
From the component, you can access the dynamic part of the URL using the hook
useParams
.The useParams hook returns an object of key/value pairs of the dynamic params from the current URL that were matched by the
//... import { useParams } from "react-router-dom"; //... function UserDetails() { const { userId } = useParams(); //useParams returns an object console.log(userId); console.log(typeof userId); //String (url params are always strings) //... //... }
-
Finally, don't forget to provide a way for the user to reach those dynamic routes.
For example, a component to display a list of available resources:function UsersList() { return ( <> <h3>List of users in our DataBase:</h3> {usersArr.map((user) => { return ( <div className="card user"> <h3>{user.name}</h3> <p>Id: {user.id}</p> <Link to={`/users/${user.id}`}>More details</Link> </div> ); })} </> ); }
Example:
- You can find an example here
Steps:
-
Create the route with the following syntax:
<Route path="/pizzas" element={<PizzasList />} />
-
In the component corresponding to that route, can use
useSearchParams
to read the query string. For example://... import { useSearchParams } from "react-router-dom"; //... function PizzasList() { const [searchParams, setSearchParams] = useSearchParams(); const maxPrice = searchParams.get("maxPrice"); console.log(maxPrice); console.log(typeof maxPrice); //String (search params are always strings) //... //... //... }
-
Finally, remember to provide a way for the user to reach that functionality. For example:
<Link to="/pizzas?maxPrice=12">Find pizzas with max price 12</Link> <Link to="/pizzas?maxPrice=15">Find pizzas with max price 15</Link>
A
<Navigate>
element changes the current location when it is rendered.
Example:
function MyComponent(props) {
//...
if (!props.isLoggedIn) return <Navigate to="/error" />;
return (
<div>
<h1>Main Title</h1>
{/* */}
</div>
);
}
To redirect the user programmatically (for example, when the user submits a form, once you get the response from the API), you can use the custom hook useNavigate
.
The useNavigate hook returns a function that lets you navigate programmatically.
For example:
//...
import { useNavigate } from "react-router-dom";
//...
function PizzaDetails(){
const navigate = useNavigate();
const deletePizza = () => {
axios.delete(API_URL + "/pizzas/" + pizzaId)
.then( response => {
console.log("your pizza was deleted....");
navigate("/"); //send the user to the homepage
})
.catch((e) => {
console.log("oops...", e);
});
}
//...
}
Example with Nested Routes:
https://stackblitz.com/edit/react-y43mfi?file=src/App.js