Callback Ref

by Allie Yu

HTML

<div id="root">
  <!-- This element's contents will be replaced with your component. -->
</div>
<!-- React -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react.js"></script>

<!-- ReactDOM -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react-dom.js"></script>

<!-- Redux -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.6.0/redux.min.js"></script>

<!-- ReactRedux -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/4.4.6/react-redux.min.js"></script>

JavaScript

//React will call the ref callback with the DOM node when the component mounts, when the component un-mounts, it will call it with null.
class App extends React.Component {
    state = { value: ''}
    
  handleSubmit = e => {
    e.preventDefault();
    this.setState({ value: this.textInput.value})
    //The callback is used to store a reference to the DOM node in an instance property. When we want to make use of this reference, using this.textInput.value
  };

  render() {
    return (
      <div>
        <h1>React Ref - Callback Ref</h1>
        <h3>Value: {this.state.value}</h3>
        <form onSubmit={this.handleSubmit}>
          <input type="text" ref={e => this.textInput = e} />
          <button>Submit</button>
        </form>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

//2
//pass ref from a parent component to a child component using callbacks.
//create "dumb" component that will render a simple input
const Input = props => {
  return (
    <div>
      <input type="text" ref={props.inputRef} />
    </div>
  );
};

class App extends React.Component {
  state = {
    value: ""
  };

  handleSubmit = event => {
    this.setState({ value: this.inputElement.value });
  };

  render() {
    return (
      <div>
        <h1>React Ref - Callback Ref</h1>
        <h3>Value: {this.state.value}</h3>
        <Input inputRef={el => (this.inputElement = el)} />
        <button onClick={this.handleSubmit}>Submit</button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));