Autoplay

    Understand React.Children Utilities

    Joe MaddaloneJoe Maddalone

    The data contained in this.props.children is not always what you might expect. React provides React.children to allow for a more consistent development experience.

    reactReact
    0.14 - 16
    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 In a number of situations, you may want to iterate over the children of your components. To illustrate that, I'm going to say let items = this.props.children. I'm going to map over those. I'm going to take in a child and return the same child. We'll log out our items.

    00:22 In this case, in our parent component, which we're rendering in our app component, we have two children, each a div, one with a class name of child A, and another with a class name of child B. We're expecting those to be represented in this items variable. We do in fact see that. We've got an array with two objects representing each of children.

    00:41 However, if we remove the second child and try to rerun the same code, we're going to get an error that says, "Map is not a function of props.children." If we log out this.props.children before we call a map method, we're going to see that our children in this case is actually a single object.

    01:02 To solve that, React provides us with react.children and a number of methods that we can attach to that. Map is in fact one of them. Here we will say map. This is going to take two arguments instead of just the mapping function.

    01:19 The first argument is going to be the actual children, then the following will be a mapping function. We'll save that. Even with one child, we do get an array with a single object. In this particular case with mapping, and the fact that I'm simply returning the component, we can actually call react.children.2array, pass in our props.children. Sign out the items.

    01:48 We'll get the exact same result, with one or more children. There it is with two, and we get that right there. In addition to map and to array, we also have a standard for each, same signature. In this case, let's log something out since this won't return an array.

    02:08 We'll say child.props.classname, save that. We should see child A and child B, and we do.

    02:17 Another method that we have is react.children.only. This is going to return a single child. If it's more than one child, it will throw an error. Let's assign that to items. I'm expecting an error, which we did get, because we have more than one child. We're going to delete the second child, and now we've got a single child.

    Discuss

    Discuss