Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Extracting Private React Components

    Merrick ChristensenMerrick Christensen

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

    reactReact
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss