Nested Routes with React Router V4 / V5

Nested Routes with React Router v4/v5

React Router is a popular library for handling routing in React applications. With the release of React Router v4, the way we handle nested routes has changed. In this blog post, we will explore how to implement nested routes using React Router v4/v5 and provide code snippets for each solution.

Solution 1: Using the Route component

The Route component in React Router v4/v5 allows us to define nested routes within our application. We can nest Route components inside each other to create a hierarchy of routes.

Here’s an example of how to define nested routes:


import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

const App = () => (







);

const Users = () => (

Users


);

const UserList = () => (

User List

{/* Render a list of users */}

);

const UserDetails = ({ match }) => (

User Details

User ID: {match.params.id}
{/* Render user details based on the ID */}

);

export default App;

In this example, the Users component acts as the parent route for the nested routes. The UserList component is rendered when the “/users” route is matched, and the UserDetails component is rendered when a dynamic route like “/users/:id” is matched. The match object is passed as a prop to the UserDetails component, which contains the URL parameters.

Solution 2: Using the render prop

Another way to handle nested routes in React Router v4/v5 is by using the render prop. The render prop allows us to define inline functions for rendering components based on the current route.

Here’s an example of how to use the render prop:


import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

const App = () => (




(

Users


)} />


);

const UserList = () => (

User List

{/* Render a list of users */}

);

const UserDetails = ({ match }) => (

User Details

User ID: {match.params.id}
{/* Render user details based on the ID */}

);

export default App;

In this example, the render prop is used to define an inline function that renders the nested routes for the “/users” route. The UserList and UserDetails components are rendered within this function.

Both solutions allow us to handle nested routes in React Router v4/v5. Choose the one that suits your project’s requirements and coding style.

That’s it! You now know how to implement nested routes with React Router v4/v5. Happy coding!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *