Extracting Private React Components

Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 5 years ago

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.

egghead
egghead
~ 2 hours ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today