Implement Nested Routes in React.js – React Router DOM V6
In this article, we will be building a simple React.js application to implement nested routing in the current version of react-router that is React Router DOM version 6. We use nested routing in our application so that a parent component has control over its child component at the route level.
Prerequisites: The pre-requisites for this project are:
Creating a React application:
Step 1: Create a React application by typing the following command in the terminal:
npx create-react-app nesting-demo
Step 2: Now, go to the project folder i.e nesting-demo by running the following command:
Project Structure: It will look like this:
Step 3: Let’s install the React Router DOM npm package required for this project:
npm install react-router-dom
Example: In this file, we will be implementing the routing logic. Previously in the React Router DOM V5, we used to have <switch> element but we won’t be using that now. One of the features of React Router DOM V6 is that it now comes with a <Routes> element. This is an upgrade as it comes with features like relative routing and linking, automatic route ranking, and nested routes and layouts. In our app, we will have two routes, one for the Home page and another for the Courses page. Under the Courses page, we will have again two routes, one for the Search component and the other for the List component. Thus we need to implement nested routing in the Courses page in order to render the selected component.
We put the paths named ‘search’ & ‘list’ under the ‘courses’ path, so the URL will localhost:3000/courses/search and localhost:3000/courses/path respectively.
Let’s create the Search and List component. Create a folder named Components and under that create two files ‘Search.js’ and ‘List.js’.
Now let’s create the two pages required for this app. Create a folder named Pages and under that create two pages named ‘Home.js’ and ‘Courses.js’.
Filename Courses.js: In this file, we will be using the new <Outlet> element to render two child components named ‘Search’ and ‘List’.
We used an <Outlet> element as a placeholder. An <Outlet>, in this case, is how the Courses component renders its child routes. So the <Outlet> will render either a Search component or List component depending on the current location.
React Router DOM V6 comes with more features apart from simplified nested routing, you can check it out here at its official documentation.
Step to Run Application: Run the application using the following command from the root directory of the project.
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: