Selected topic
React Router
Prefer practical output? Use related tools below while reading.
=======================
React Router is a popular library for client-side routing in React applications. It allows you to navigate between different routes, manage the URL, and provide a better user experience.
The Route component is the core of React Router. It defines a single route that matches a specific path in the URL.
jsx
import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';function App() {
return (
<BrowserRouter>
<Route exact path="/" component={Home} />
{/ Other routes go here /}
</BrowserRouter>
);
}
function Home() {
return <h1>Home Page</h1>;
}
Route component is used to render the Home component when the URL matches the / path.The Route component accepts several props that can be used to customize its behavior:
jsx
import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';function App() {
return (
<BrowserRouter>
<Route path="/users/:id" component={User} />
{/ Other routes go here /}
</BrowserRouter>
);
}
function User({ match }) {
const id = match.params.id;
// Render user details
}
Route component is used to render a User component when the URL matches /users/:id, where :id is a parameter.You can configure multiple routes using the Routes component:
jsx
import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
{/ Other routes go here /}
</Routes>
</BrowserRouter>
);
}
Routes component is used to group multiple routes together. Each route is defined using a separate Route component.React Router's Route component provides an essential building block for client-side routing in React applications. By understanding how to use the Route component and its props, you can create complex routing configurations that enhance user experience.