How to safely inject props into React children?

14,483

Best way to add new props or override existing ones is to map your children props and clone each element using React.cloneElement.

Nice article to read about react children.

React.Children.map(this.props.children, child =>
    React.cloneElement(child, { newProp: 'value', existingProp: 'value' }));

You could also use children as a function. This way u can also add your props.

Example:

// Root Component
const Parent = () => { 
  const onClose = () => console.log('I am on Close Prop');

  // Pass OnClose to children
  return <MyComponent>{ children(onClose) }</MyComponent>
}

// MyComponent
const MyComponent = () => {
// Pass OnClose to children
  return (
    <div>
      {/* children below */}
      {(onClose) => (
          <FormComponent
              myNewProp={onClose}
          />
      )}
    </div>
);

}
Share:
14,483
yawn
Author by

yawn

Updated on June 14, 2022

Comments

  • yawn
    yawn almost 2 years

    I am building a React component which delays the unmounting of its children in order to animate them. When unmounting, I would like to pass in an additional prop (for example, a data-attribute or a class name) in order to handle animations.

    This is a specific instance of a general situation where I want override certain properties of children. I have come to realize that the following pattern does exactly what I want:

    this.props.children.map(child => 
        <child.type key={child.key} 
                    ref={child.ref}
                   {...child.props} 
                   // add my props into children here
                   data-leaving={true} />)
    

    Instead of returning the child element, I return a new element of the same type and with the same props. I can then add or remove any props I want!

    However, this is undocumented and feels very hacky. I would like to know if this is safe to use in every case.

    Note that I am aware of alternatives (for example, accepting a function which returns the children instead of children directly) but this gives the most convenient interface by far.