4elements

blog

Understanding Nested Routing in React

React is a JavaScript library built by Facebook for building user interfaces. If you are new to React, I would recommend reading one of our earlier tutorials on getting started with React. In this tutorial, we'll discuss how to handle nested routing in a React web application.

app.js is the file where our React code would reside. Create a file called app.js inside the ReactRouting folder. Import the required react libraries in app.js. Create a component called App having a div with some text. Render the component using the render method. Here is how the basic app.js file would look:

Once the server has been restarted, you should be able to view the React app running on http://localhost:8080/.

Handling Routing in React

We'll be making use of react-router to implement routing and nested routing. First, install react-router in our project.

npm install react-router --save

Now we have react-router installed in our project. Let's create a couple of views to implement routing. Inside the app.js file, create two components called view1 and view2. Here is how the code would look:

Try clicking on the View1 and View2 links, and it should navigate to the appropriate components.

Nested Routes in React

We already have an App component which displays the header text. Suppose we want the menu click to display the appropriate view, but we want it to be rendered inside the App component.

We want the navigation menu to be available across all pages. In order to achieve this, we'll try to nest our react components View1 and View2 inside the App component. So whenever the View1 is rendered, it's displayed inside the App component.

Now modify the router config and place the View1 and View2 route config inside the App component route.

Save the above changes and restart the server, and you should be able to view the application. Click on the menu items listed, and each when clicked should render nested inside the App component.

Wrapping It Up

In this tutorial, you saw how to implement nested routing in a React application using react-router. You can develop small independent components and then use the components to create larger applications. Making it possible to stitch up small components into large applications is what makes React really powerful.

React is becoming one of the de facto platforms for working on the web. It’s not without its learning curves, and there are plenty of resources to keep you busy, as well. If you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato marketplace.

Source code from this tutorial is available on GitHub. Let us know your suggestions and thoughts in the comments below.