⚠️ This lesson is retired and might contain outdated information.

React Router: Nested Routes

Joe Maddalone
InstructorJoe Maddalone
Share this video with your friends

Social Share Links

Send Tweet

Since react-router routes are components, creating nested routes is as simple as making one route a child of another in JSX. In this lesson we'll explore nesting routes and accessing the children of parent routes.

[00:00] When we want to create nested routes with React router, it's as simple as just placing a route inside of another route component. We've got our little application here. We've got home, about, and contact, each as its own route.

[00:13] What I'm going to do is take about and make it a child of home. I'm going to take contact, and I'm going to make it a child of about. We can actually get rid of the absolute paths here. Up here, let's see, about is going to stay the same.

[00:37] Contact is going to become /about, /contact. When we save that, nothing much is really going to happen, because these components need to know about their children. In home, we're going to take in props.

[00:52] We're actually going to do the same thing in about, since we need to get to the component's children. Here in home, right after links, we're going to say props.children, and in this case, that is going to be the about component.

[01:07] In about and contact, I'm going to go ahead and get rid of the links component, because it's just going to get very confusing. In the about component, I'm going to go ahead and drop props children, which is, in fact, going to be contact.

[01:23] Let's go and just save that and try it out. We're here on the home route. When we go to about, we've got our home component, represented by this route right here. Of course, we've got our links, and then we've got our props children, which is the component that is rendered at the about path. It's our about component.

[01:44] When I go to contact, we've got all three components on the page. That's represented here by the props children in our about component, and that props children is, in fact, the contact component. We've got home, which has a child of about, which has a child of contact.