This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Extracting Private React Components

1:52 React lesson by

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

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

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

Avatar
Martin

This is better known as a stateless component in the React community.

In reply to egghead.io

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.

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.

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.

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.


Featured course:

Building apps with Ionic 2

Building apps with Ionic 2

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?