The Children Prop
Let's suppose that we're building a custom button component. It should look and act just like a regular HTML button, but it should have a red background and white text.
We could write it like this:
function RedButton({ contents }) { return ( <button style={{ color: 'white', backgroundColor: 'red', }} > {contents} </button> );}
…And then we'd use it like this:
root.render( <RedButton contents="Don't click me" />);
This works… but it feels a bit funny, doesn't it? It's quite different from how we use a typical HTML button, where the content goes in-between the open and close tags:
<button> Don't click me</button>
As a nice bit of , React lets us do the same thing with our custom components:
root.render( <RedButton> Don't click me </RedButton>);
When we do this, we can access the children through the children
prop:
function RedButton({ children }) { return ( <button style={{ color: 'white', backgroundColor: 'red', }} > {children} </button> );}
This is a quality-of-life thing that React does for us. When we pass something between the open and close tags, React will automatically supply that value to us under children
.
We can see this when we examine the React element produced:
Code Playground
- {"type": "div","key": null,"ref": null,"props": {"children": "Hello World"},"_owner": null,"_store": {}}
children
is a special value, a “reserved word” when it comes to props.
But it's not that special. I think a lot of newcomers to React think that children
is somehow distinct or different from other props. In fact, it's exactly the same.
If we wanted to, we could pass children
in the "traditional" way. It's clunky, but the outcome is the same:
// This element:<div children="Hello world!" />
// …is equivalent to this one:<div> Hello world!</div>
And so, we're given a special bit of syntax, to make JSX feel more like HTML, but fundamentally, the children
prop is the same as any other prop. There's nothing special or magical about it.