This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Use React the cloneWithProps method to interact with child components

3:02 React lesson by

this.props.children allows child components to pass through, but in order to interact with or add new functionality to them React.addons provides cloneWithProps.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

this.props.children allows child components to pass through, but in order to interact with or add new functionality to them React.addons provides cloneWithProps.

In React, this.props.children can be a little deceiving. Just to illustrate that, I've got a really simple application here, called "Group." I've got InitialState returning selectedValue of None. I've got a selectItem method which is going to set the state to whatever's passed in to it. I'm assigning items to this.props.children.

Here it is on the right. What I want to do is every time you click on this, I want to update "You Selected" to "You Selected" whatever the value of these are. That gives me a really nice structure like this, where I've got this Group component and then I'm passing in these children. All I need to do is add that functionality to those children and grab this value from them. The first thing that you're going to try, just to walk through this...This isn't actually going to work, but you're going to try to map these children. Should say "child."

What you'll end up trying to do is say "child.onClick = this.selectItem." Return...Not this...child. We'll bind that to the context of this. You're going to expect that to work. Let's try it out really quick. Let's reload. It does not work. The reason is that this.props.children is actually a descriptor of those children. It's not the actual child. You can't change anything on it. You can't change a name. You can't change a class. You can't change anything.

The solution to this is React.addons.cloneWithProps. We're going to return that. The first argument there is your child element, whatever the component might be. The second argument is an object where you can extend that child.

I'm just going to take this. Drop it in right here. I'm going to say, "onClick." This is a key, rather than an assignment. Save that. Now we'll reload over here. Ah. That's not working. You know what? I did not bind that. Bind null is probably fine, and child.value. Now we're actually passing in that prop.

Now we get our expected results. The thing to understand here is, again, this.props.children is a description of the children. It's not the actual objects. What you end up doing is taking that description and creating a new object or a new component with cloneWithProps. Again, while that sounds expensive with other libraries, because of the virtual DOM, it really costs us nothing.

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