this.props.children.md
February 15, 2023 · View on GitHub
What even is ‘children’?
children is a special property of React components which contains any child elements defined within the component, e.g. the divs inside Example above. {this.props.children} includes those children in the rendered result.
What are the situations to use the same
You'd do it when you want to include the child elements in the rendered output directly, unchanged;
The React docs and the simple example - https://codepen.io/gaearon/pen/ozqNOV say that you can use props.children on components that represent ‘generic boxes’ and that ‘don’t know their children ahead of time’.
My simple explanation of what this.props.children does is that it is used to display whatever you include between the opening and closing tags when invoking a component.
A simple example
Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no 'this' keyword so just use props.children
const Picture = props => {
return (
<div>
<img src={props.src} />
{props.children}
</div>
);
};
// App.js
function App () {
render() {
return (
<div className='container'>
<Picture key={PIcture.id} src={picture.src} >
// whatever is placed here is passed as props.children
// Like I can place a <div></div> here and it will be rendered as a child to the Picture component.
// Note, I am not including this extra divs in the Picture componet, but here in App component, where I am calling the picture component.
</Picture>
</div>
)
}
}
You might want to assume that App.js will render as its html within the App.js, but it’s already in another component Picture. It won’t render whatever goes in between in the App.js. UNLESS OFCOURSE I PUT {props.children} inside the Picture component itself
Anything inside the
This de-couples the
So basically I take code out of
https://medium.com/javascript-in-plain-english/how-to-use-props-children-in-react-7d6ab5836c9d