Skip to content

Maintaining ref prop through React.cloneElement() #8873

@pvienneau

Description

@pvienneau

React's 0.13 RC suggests that ref prop on components pushed through React.cloneElement() will allow for two parents to maintain ref props to the same child.

I've tried to replicate this behaviour in a CodePen, but I am not able to maintain two ref references to the same child (ie the ancestor component's ref gets nulled).

Here is the jist of the code, working code found here:

class ChildComponent extends React.Component{
  constructor(props){
    super(props);   
  
    this.onClick = this.onClick.bind(this);
    this.extendsChildren = this.extendChildren(this);
  }
  
  onClick(e) {
    e.preventDefault();
    
    try{
      alert(this._input.value);
    }catch(e){
      alert('ref broken :(');
    }
  }
  
  extendChildren(){
    return React.Children.map(this.props.children, child => {
      return React.cloneElement(
        child,
        {
          ref: ref => this._input = ref
        }
      );
    });
  }
  
  render() {
    return(
      <div>
      <button onClick={this.onClick}>
        ChildComponent ref check
      </button>
      {this.extendChildren()}
    </div>
    );
  }
}


class AncestorComponent extends React.Component{
  constructor(props){
    super(props);
    
    this.onClick = this.onClick.bind(this);
  }
  
  onClick(e) {
    e.preventDefault();
    
    try{
      alert(this._input.value);
    }catch(e){
      alert('ref broken :(');
    }
    
  }
  
  render() {
    return (
    <div>
        <p>
          The expected behaviour is that I should be able to click on both Application and ChildComponent check buttons and have a reference to the input (poping an alert with the input's value).
        </p>
      <button onClick={this.onClick}>
        Ancestor ref check
      </button>
      <ChildComponent>
        <input ref={ref => this._input = ref} defaultValue="Hello World"/>
      </ChildComponent>
    </div>
    );
  }
}

Has this behaviour been dropped/never implemented since the above RC? Or am I doing something wrong?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions