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.
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'spropTypes
says it is.
And:
We recommend that most of the time you use the general
ReactNode
type for yourthis.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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With