Selected topic

Route

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.

Route Component


-------------------

The Route component is the core of React Router. It defines a single route that matches a specific path in the URL.

Example: Simple Route


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>;
}


In this example, the Route component is used to render the Home component when the URL matches the / path.

Props


---------

The Route component accepts several props that can be used to customize its behavior:

  • path: The URL path that should match for this route.
  • exact: If true, the route will only match if the URL is an exact match (i.e., it includes all characters).
  • component: The React component to render when this route matches.
  • render: A function that returns a React element when this route matches.

Example: Route with Parameters

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
}


In this example, the Route component is used to render a User component when the URL matches /users/:id, where :id is a parameter.

Route Configuration


----------------------

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>
);
}


In this example, the Routes component is used to group multiple routes together. Each route is defined using a separate Route component.

Conclusion


----------

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.