Skip to content

this.props.children #13564

@andrevenancio

Description

@andrevenancio

Do you want to request a feature or report a bug?
FEATURE?

What is the current behavior?
AMBIGUOUS.

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn't have dependencies other than React. Paste the link to your JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new) example below:

What is the expected behavior?

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?
EVERYTHING

Hi all.

Maybe this isn't a feature request, but more an API choice which I would like to put it the open and maybe try to understand the decision that led to the implementation. So apologies in advance if I just don't get it :)

Why does this.props.children either render a Child or an array of children? Why can't this be an array of children all the time?

Take this as an example of a Parent class:

import React, { PureComponent } from 'react';
class ParentExample extends PureComponent {
    render() {
        return (
            <div>
                { this.props.children.map((Child, i) => (
                    <Child key={i} />
                ))
                }
            </div>
        );
    }
}

Now if you do something like:

return (
    <ParentExample>
        <SomeComponent />
        <SomeOtherComponent />
    </ParentExample>
);

You have no problems, cause your children prop inside the ParentExample is an array. However if you decide that you just want to pass 1 child into it like so:

return (
    <ParentExample>
        <SomeComponent />
    </ParentExample>
);

You'll get an error because the children prop inside the ParentExample is now a direct reference to the SomeComponent instead of an array of children.

Doesn't it make more sense to always return an array?

Having to do this sanitation all the time before rendering the children is a bit silly... Now I might totally be missing the point here, but shouldn't the name itself be a clue? this.props.children children... an array of children. Can be 0, can be 1 can be N...

Opinions?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions