Sunday, April 22, 2018

Callback Refs in React 16.3

Callback Refs were introduced before React 16.3.
React 16.3 continues to support the callback refs from the previous versions. In createRef API we create a reference and set it to the element using the ref attribute. In callback refs we instead set the ref attribute to a function which receives the component/element reference as an argument and sets the reference.

The below example shows how to define and use callback refs.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.textRef = null;
    this.setTextRef = element => {
      this.textRef = element;
    };
  }

  componentDidMount() {
    this.textRef.focus();
  }

  render() {
    return (
      <div>
        <input type="text" ref={this.setTextRef} />
      </div>
    );
  }
}

Search Flipkart Products:
Flipkart.com

No comments: