What is React Router Routes
This article provides a clear overview of how routing works in React
applications using the React Router library. It covers the core concepts
of the <Routes> and <Route>
components, explaining how they map browser URLs to specific React
components to enable seamless navigation without page reloads.
In a traditional multi-page website, navigating to a new URL requests a complete HTML document from the server. React applications, however, are typically Single Page Applications (SPAs). To handle navigation without reloading the entire page, React developers use a library called React Router. This library mimics traditional navigation by dynamically rendering different components based on the browser’s current URL.
The core of this navigation system relies on two essential
components: <Routes> and
<Route>.
The Routes Component
The <Routes> component acts as a container for all
the individual routes in your application. Whenever the URL changes,
<Routes> looks through all of its child
<Route> elements to find the one that matches the
current path. Once a match is found, it renders only that specific
component, ignoring the others. This ensures that only the relevant user
interface is displayed.
The Route Component
Within the <Routes> container, you define
individual paths using the <Route> component. The
<Route> component requires two primary properties: *
path: A string that specifies the URL path
(e.g., /about or /contact). *
element: The React component that should
render when the browser URL matches the path.
A Basic Example
Here is a simple example of how these components are structured in a React application:
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}In this example, if a user visits the root URL (/), the
<Home /> component is displayed. If they navigate to
/about, the <About /> component renders
instead.
Dynamic Routing
React Router also supports dynamic routing, which allows you to match
URLs that change based on data, such as user IDs or product names. This
is done by using a colon (:) in the path definition:
<Route path="/profile/:username" element={<UserProfile />} />In this case, any URL like /profile/john or
/profile/sarah will match this route, and the
UserProfile component can access the dynamic
username value to fetch and display the correct data.