Home

this.props.children

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.


Example...

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


Top

Code Example (App.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')
);

Here we have, in the return section of the App class, a call of the List class (that is imported from List.js).

Inside the call of the List class are just some line items for an unordered list (<li>...</li>).

It ALSO includes a property to send (called TYPE) so it can include the headers in the List class.

Code Example (List.js)

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>

    );
  }
}

Because the ONLY items inside the call to the List class (in App.js) are just the (<li>...</li>) items then that is all that gets added to the the above as the {this.props.children}.

And because the call to the List class (in App.js) happens twice, with different <li>...</li>) items then that means we get two different unordered lists displayed.

First unordered list
Favorite Living Musician

Sachiko M
Harvey Sid Fisher

Second unordered list
Favorite Living Cat Musician

Nora the Piano Cat


Top