Extracting Private React Components

Share this video with your friends

Social Share Links

Send Tweet

In this lesson we leverage private components to break our render function into more manageable pieces without leaking the implementation details of our component.

[00:00] Let's start by implementing the render function for our user list component. In our render function we return a block of JSX code. This component is passed a list of users as props. This.props.users.map takes in a user and for each user we want to return a list element that contains the user's name. React requires that we key each element during the iteration. Let's jump over to Chrome and see what this looks like.

[00:36] Now I want to add a title to this component. Let's see what this looks like in Chrome. In this example, the H1 here maps to the users here, then we're iterating it over each user and putting in a div with the user's name. As our render function grows, it makes sense to break it into smaller more maintainable pieces.

[00:59] A technique for this is to grab the piece you want to extract. So I'm going to copy this line, I'm going to paste it above our component. Then I'm going to wrap it in what's called a private component. You give it a name, in this case userListItem that takes in a user. For each user we're going to return this list item. We no longer need to have the key within here, because we're going to use the key in our map below.

[01:26] Then to use our component, we come down to the part that we extracted the code and we drop in our component name providing the user and giving it a key. Let's jump over to Chrome and make sure this works. So now each user is actually a userListItem component which renders the div that we had before.