Search code examples
reactjscomponentsreact-propschildren

Is there a way to pass props to a contained component in react?


If I have a component defined like so:

export default class LinkContainer extends React.Component {
  render() {
    return (
      <div>
        <a href={this.props.baselink}>
          <h3>{this.props.title}</h3>
        </a>
        {this.props.children}
      </div>
    )
  }
}

Is there a way to pass this.props.baselink to all of the components in this.props.children?


Solution

  • You can do this by using cloneElement. Map over your children and clone each one, passing a second argument to the cloneElement, which will act as props. isValidElement is used in this example in case you have children that can't be cloned, such as a text node.

    export default class LinkContainer extends React.Component {
      render() {
        return (
          <div>
            <a href={this.props.baselink}>
              <h3>{this.props.title}</h3>
            </a>
            {Children.map(this.props.children, (child) => {
              if (!isValidElement(child)) return child;
              return cloneElement(child, { baselink: this.props.baselink });
            })}
          </div>
        );
      }
    }
    

    Here it is in action: https://codesandbox.io/s/vigorous-dream-9650n