1

I am trying to create a React class whose instances' state changes affect their child components' props. It is easy to realize it if the child components are instantiated within the parent instances' render() method. However, is there a way that I can pass the parent instances' state values to this.props.children passed to the render() method as already-instantiated React components (see code below)?

const Child = class extends React.Component{
  render(){
    return (
      <div>
        {this.props.val}
      </div>
    )
  }
}

const Parent = class extends React.Component{
  constructor(){
    this.state = {val: undefined};
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick(e){
    this.setState({val: e.nativeEvent.offsetY});
  }
  render(){
    const children = this.props.children.map( child => (
      child instanceof Object 
      ? child // how to pass this.state.val to this instance?
      : <Child val={this.state.val}></Child> // passing this.state.val is easy
    ) );

    return (
      <div>
        {children}
      </div>
    );
  }
}

const enhancedParent = class extends React.Component{
  render(){
    return (
      <div>
        {this.props.val} // or this.state.val, or anything else that receives this.state.val from its parent
      </div>
    );
  }
}
Capybara
  • 190
  • 7

1 Answers1

0

If I understand correctly, you are trying to add extra properties to children like this:

<Parent>
   <Child/>
</Parent>

But Parent want to render its children like this:

<Child val={1}/>

The solution is React.cloneElement.

render(){
    return (
        <div>
            {{React.cloneElement(this.props.children, {
                val: this.state.val
            })}}
        </div>
    );
}
Mihályi Zoltán
  • 822
  • 6
  • 11