You can use props.children in React in order to access and utilize what you put inside the open and closing tags when you are creating an instance of a component.
For example, if I have a Button component, I can create an instance of it like this: <Button>HI!<Button> and then inside of the Button component, I could access that text with props.children. You can also use this to create components that wrap other components -- <Container><Button /></Container> for example.
function Button (props) {
return <button>{props.children}</button>
}
I can then instantiate the component with <Button>Click Me!</Button> and then a button with the text click me would display on the page.
For a layout, I could do something like:
function Container ({ children }) {
return <div style={{ maxWidth: 800px, margin: 0 auto }}>{children}</div>
}
Note: in this example, I'm destructuring the props object, so I can use children directly.
And then to instantiate it I could do:
<Container>
<h1>Welcome to my App</h1>
<p>Hello, hi, this is my paragraph</p>
</Container>
Normally in order to pass props from one component to another, you need to do <Button label="hello" /> and then use props.label in the component, but React children is more flexible and allows you to mirror HTML more closely within your JSX.
Latest comments (7)
These concepts have been bugging me until now. Now I got the hang of it.
Thanks for the clear and concise explanation.
Time to teach these children a lesson. (pun intended)
In principle
childrenin React plays a similar role toslottedelements in DOM templates (Web Components) - butchildrenisn't as powerful as Vue's scoped slots (or Svelte's named slots) which can bind external data into slotted elements.For that purpose renderProps (or component injection) are used in React (example gist).
That might explain why the
childrenprop is so infrequently used in contemporary React.Literally any React element which can have nested elements uses
childrenprop.Just used children two times
auseschildrenfor 'test'divuseschildrenfor the aboveUnder the old terminology both
divandaare "ownees" of the owner custom component.I was trying to point out that custom components don't often use the
childrenprop for elements nested by the owner because of their static nature. Often the component needs to render data into the fragment (much like a template) which requires a "function as child component", a render prop, or injected component....half asleep, I click onto DEV, see
Using Children in React, and forgot all my programming knowledge briefly. So I saw literal children being called over for a work project.Sips coffee, glad to leave the website building to Ali Spittel and other brilliant minds.
Likewise. I was half asleep too and thought the same. This, people, is why you should get sufficient sleep every night.
HAHA that's amazing