React Router is a standard library for routing in React applications. It enables the navigation among views of various components in a React application, allows changing the browser URL, and keeps the UI in sync with the URL.
Introduction
Let’s analyze “Browser Router” and then explore React Router in depth to help you get started.
This code is implementing the Browser Router pattern in React Router v6, which uses the HTML5 history API to keep your UI in sync with the URL.
React Router Basics
Installation
To use React Router in your project, install it using npm or yarn:
1 2 3
npm install react-router-dom # or yarn add react-router-dom
Router Types
React Router offers several router types, each suited for different environments:
1. BrowserRouter
The BrowserRouter uses the HTML5 history API (pushState, replaceState, and the popstate event) to keep your UI in sync with the URL.
1 2 3 4 5 6 7 8 9
import { BrowserRouter } from'react-router-dom';
functionApp() { return ( <BrowserRouter> {/* Your routes go here */} </BrowserRouter> ); }
2. HashRouter
The HashRouter uses the hash portion of the URL (i.e., window.location.hash) to keep your UI in sync with the URL.
1 2 3 4 5 6 7 8 9
import { HashRouter } from'react-router-dom';
functionApp() { return ( <HashRouter> {/* Your routes go here */} </HashRouter> ); }
3. MemoryRouter
The MemoryRouter keeps the history of your “URL” in memory (does not read or write to the address bar). Useful for testing and non-browser environments like React Native.
1 2 3 4 5 6 7 8 9
import { MemoryRouter } from'react-router-dom';
functionApp() { return ( <MemoryRouter> {/* Your routes go here */} </MemoryRouter> ); }
Route Configuration in React Router v6
In your code, you’re using the v6 pattern with the Routes and Route components.
Routes Component
The Routes component replaced the old Switch component from v5. It’s responsible for rendering the first Route that matches the current URL.
Route Component
The Route component defines a path and the element to render when that path matches the current URL.