Being a beginner to React world, I want to understand in depth what happens when I use {this.props.children}
and what are the situations to use the same. What is the relevance of it in below code snippet?
render() {
if (this.props.appLoaded) {
return (
<div>
<Header
appName={this.props.appName}
currentUser={this.props.currentUser}
/>
{this.props.children}
</div>
);
}
}
This question is related to
javascript
reactjs
react-redux
frontend
I assume you're seeing this in a React component's render
method, like this (edit: your edited question does indeed show that):
class Example extends React.Component {_x000D_
render() {_x000D_
return <div>_x000D_
<div>Children ({this.props.children.length}):</div>_x000D_
{this.props.children}_x000D_
</div>;_x000D_
}_x000D_
}_x000D_
_x000D_
class Widget extends React.Component {_x000D_
render() {_x000D_
return <div>_x000D_
<div>First <code>Example</code>:</div>_x000D_
<Example>_x000D_
<div>1</div>_x000D_
<div>2</div>_x000D_
<div>3</div>_x000D_
</Example>_x000D_
<div>Second <code>Example</code> with different children:</div>_x000D_
<Example>_x000D_
<div>A</div>_x000D_
<div>B</div>_x000D_
</Example>_x000D_
</div>;_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
<Widget/>,_x000D_
document.getElementById("root")_x000D_
);
_x000D_
<div id="root"></div>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
_x000D_
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; and not if you didn't.
props.children
represents the content between the opening and the closing tags when invoking/rendering a component:
const Foo = props => (
<div>
<p>I'm {Foo.name}</p>
<p>abc is: {props.abc}</p>
<p>I have {props.children.length} children.</p>
<p>They are: {props.children}.</p>
<p>{Array.isArray(props.children) ? 'My kids are an array.' : ''}</p>
</div>
);
const Baz = () => <span>{Baz.name} and</span>;
const Bar = () => <span> {Bar.name}</span>;
invoke/call/render Foo
:
<Foo abc={123}>
<Baz />
<Bar />
</Foo>
Source: Stackoverflow.com