React Router

Routing means using a URL to navigate between different pages in your application. The React library does not provide a specific routing solution, but React Router is the most popular one.

Add React Router to your app!

Install the required libraries:

yarn add react-router-dom

Update the main.jsx file:

import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; + import { BrowserRouter } from "react-router-dom"; ReactDOM.createRoot(document.getElementById("root")).render( + <BrowserRouter> <App /> + </BrowserRouter> );

Switch between routes!

Import the Routes and Route components.

import { Routes, Route } from "react-router-dom";

Declare the routes! (Usually done in the App.js file):

import { Routes, Route } from "react-router-dom"; function App () { return ( <Routes> <Route path="/about" element={ <div>About Us</div> } /> <Route path="/contact" element={ <div>Contact Us</div> } /> <Route path="/" element={ <div>Homepage</div> } /> </Routes> ); } export default App;

A <Routes> looks through its children <Route>s and renders the first one that matches the current URL.

You can use URL parameters as shown in the example below:

import { Routes, Route } from "react-router-dom"; import Topic from "./components/Topic"; function App () { return ( <Routes> <Route path="/topics/:topicId" element={ <Topic /> } /> <Route path="/topics" element={ <h3>Please select a topic.</h3> } /> </Routes> ); } export default App;

Using useNavigate hook for navigation

The useNavigate hook returns a function, navigate that lets you navigate programmatically.

import { useNavigate } from "react-router-dom"; function About() { const navigate = useNavigate(); const handleOnClick = () => { navigate("/"); }; return ( <> <p>About us<p> <button onClick={handleOnClick}>Return to homepage</button> </> ); } export default About;