React Router: Named Components

Joe Maddalone
InstructorJoe Maddalone

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 3 years ago

In this lesson we'll learn how to render multiple component children from a single route.

[00:00] We can render multiple components at a single route using something in React Router called named components. To get us started here, I've got a component called home, just renders home. HomeBody renders this div with the innerHTML, "This is the home body." Then we follow suit with this other component and other body.

[00:21] I'm going to create a container component. I'm just going to call that, "container." This is going to have props, and we're simply going to return a div that has an innerHTML of props.header and props.body.

[00:38] You know what, we're going to go ahead and create a links component like we have in previous tutorials. Our links component will be a nav, and we'll just have a link to our route path. We'll say home there. Then I have a link to our other path, and we'll just say other there.

[01:03] Here in our router, we are going to create our initial route/, and the component there is going to be our container. Inside that, we're going to create an index route.

[01:17] Rather than component, we're going to say components. Here, we're going to create a new object that has each of the keys that match the paths that we need. We're going to need a header and a body.

[01:34] Our header is going to be our Home component, and our body is going to be our homeBody component. Then we'll have one more route here with a path of /other. Then, again, we're going to do components, and we're going to have a header of other and a body of otherBody.

[02:03] I'll save that. So we can see, on our index route, we've got home and we've got "This is the home body" which is our homeBody component. When we switch to other, we've got our otherHeader, which is this other component, and we've got our "This is the other body," which is our otherBody component, so we can nav between the two.

Zhenyang Hua
Zhenyang Hua
~ 6 years ago

Does it has to be "body" and "header" as keywords? What decides the order of the subcomponents being rendered?

Joe Maddalone
Joe Maddaloneinstructor
~ 6 years ago

No the keys can be whatever you like, sorry if that was not clear.

The order is decided by however you lay your components out, this is covered at 0:25 in the lesson.

const Container = (props) =>
  <div>{props.header}{props.body}<Links /></div>