Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting children in defaultProps

Tags:

reactjs

I am developing a React component that contains some child components. I would like it to have a default set of children, if its element is created without specifying children (i.e. <MyContainerComponent ... /> should be equivalent to <MyContainerComponent ...><!-- some default child elements --></MyContainerComponent>).

From https://github.com/facebook/react/blob/v0.14.8/src/isomorphic/classic/element/ReactElement.js#L135, I understand that props.children will be undefined if no children are specified. Thus, I would like to rely on this and set children in the defaultProps of MyContainerComponent.

I am not sure, however, if I am coupling my decision too much with React's implementation (i.e. by design, as a user of React, is it acceptable to treat children just like any other prop that would be undefined if you did not explicitly define it). All other materials I read on children treat is as either a single element, or an array, but not potentially undefined.

I'd really appreciate a more experienced opinion.

like image 298
user56828cc2 Avatar asked Apr 20 '16 18:04

user56828cc2


1 Answers

The React project hasn't done a great job of documenting how props.children is treated, but I would say that:

it [is] acceptable to treat children just like any other prop that would be undefined if you did not explicitly define it

References:

Comments by Sebastian Markbåge:

The type of this.props.children is whatever your component's propTypes says it is.

And:

We recommend that most of the time you use the general ReactNode type for your this.props.children.

Where the definition of ReactNode includes undefined.

My interpretation is that undefined is a valid value for props.children and should be the default in general. But note that with JSX even whitespace might affect the value:

<MyContainerComponent> </MyContainerComponent>

All of this being said, as indicated by the linked GitHub issue I'm trying to get this better documented so the API contract is clear :)

like image 161
JMM Avatar answered Oct 29 '22 22:10

JMM