Every component’s props object has a property named children.
this.props.children will return everything in between a component’s
opening and closing JSX tags.
Instead of rendering a class by using a self-closing tag, eg...
<MyClass />
You could also say
<MyComponentClass >
<h1>Header Title</h1>
</myComponentClass>
So this.props.children, would equal <h1>Header Title</h1>
NOTE
If you only used it as a self-closing tag, eg...
<MyComponentClass />
then this.props.children would equal undefined
ALSO NOTE
If a component has more than one child between its JSX tags,
then this.props.children will return those children in an array.
However, if a component has only one child, then this.props.children will return
the single child, not wrapped in an array.
So, for example, we could use this.props.children to help build
this unordered list:-
Favorite Living Musician
Sachiko M
Harvey Sid Fisher
Favorite Living Cat Musician
Nora the Piano Cat
See below code examples for
App.js
List.js
import React from 'react'; import ReactDOM from 'react-dom'; import { List } from './List'; class App extends React.Component { render() { return ( <div> <List type='Living Musician'> <li>Sachiko M</li> <li>Harvey Sid Fisher</li> </List> <List type='Living Cat Musician'> <li>Nora the Piano Cat</li> </List> </div> ); } } ReactDOM.render( <App />, document.getElementById('app') );
import React from 'react'; export class List extends React.Component { render() { let titleText = `Favorite ${this.props.type}`; if (this.props.children.length instanceof Array) { titleText += 's'; } return ( <div> <h1>{titleText}</h1> <ul>{this.props.children}</ul> </div> ); } }