Fabian Zeindl Fabian Zeindl - 3 months ago 80
React JSX Question

React.cloneElement: pass new children or copy props.children?

I'm confused by the third "children" parameter of

React.cloneElement
and it's relation to
this.props.children
.

I followed this guide on higher order components and have the following code:

render() {
const elementsTree = super.render()

let myPropChange = {}

/* work on newProps... */
myPropChange.something = "nice!".

const newProps = Object.assign({}, elementsTree.props, myPropChange)

/* map children */
const newChildren = React.Children.map(elementsTree.props.children, c => something(c))

return React.cloneElement(elementsTree, newProps, newChildren)
}



  • Should I put the mapped children into my
    newProps.children
    or should I pass them as the third parameter to
    cloneElement
    ?

  • Object.assign
    copied the children from
    props
    to
    newProps
    anyway, should I skip them?

  • In the guide it says


    Components don’t have a guaranty of having the full children tree resolved.


    What does that mean in my situation? That
    this.props.children
    is not there?

  • Added 4th question: Why should I clone the props at all and not just directly edit them?


Answer

Should I put the mapped children into my newProps.children or should I pass them as the third parameter to cloneElement?

Either should be fine.

Object.assign copied the children from props to newProps anyway, should I skip them?

When using cloneElement, you don't need to copy the props yourself. You can just do React.cloneElement(elementsTree, {something: 'nice!'}).

In the guide it says "Components don’t have a guaranty of having the full children tree resolved." What does that mean in my situation? That this.props.children is not there?

I can't be sure what that article meant, but I believe the author means that your component can choose not to use this.props.children. For example, if you render <Foo><Bar /></Foo>, then Foo will receive <Bar /> in this.props.children, but if Foo doesn't use this.props.children in its render method, then Bar will never be rendered.

Why should I clone the props at all and not just directly edit them?

React elements are immutable and there's no way you can change the props after an element is created. This allows some performance optimizations in React which wouldn't be possible otherwise.

Comments