Now that you know how to render components in a React app, how do you handle rendering components only on specific URL paths to simulate navigating through different webpages on a single-page app? React Router is the answer!
React Router is the standard library for handling frontend routing in React projects. It allows you to control which components display based on the browser location. A user can also copy and paste a URL, email it to a friend, or link to it from their own website.
By the end of this reading, you should be able to:
Think about how you created server-side routes in your previous projects. For example, you might define a GET route for /users/:userId. When a user visits http://localhost:3000/users/2, this GET route would cause the server to respond with user 2's show page in HTML.
Since you are now writing single-page apps in React, you don’t want to refresh the page each time you change the browser location. Instead, you want to update the browser location and your app's display using only JavaScript. This is known as client-side routing. React Router enables this behavior.
React Router is available as an NPM package. To install it, simply run:
npm install react-router-dom
A router determines all of your project's routes, defining what should render at each path. Your project will only ever have one router. Although React Router provides specialized routers, createBrowserRouter should be your default choice.
createBrowserRouter takes an array of route objects as its argument. These route objects define all the routes for the application. By convention, the router returned by createBrowserRouter is assigned to a variable, router. This router is then passed to RouterProvider.
In App Academy projects, the router is typically set up in App.jsx like this:
// App.jsx
import {{ createBrowserRouter, RouterProvider }} from 'react-router-dom';
import Home from './components/Home';
const router = createBrowserRouter([
{{ path: "/", element: }}
]);
function App() {{
return
}}
export default App;
In this reading, you learned:
createBrowserRouter with RouterProvider to enable routing in React projectsTo deepen your understanding, explore these topics:
React Router is essential for managing navigation in React applications. By mastering its features, developers can create dynamic, user-friendly, and scalable applications.