1.

Explain “refs” in React?

Answer»

Refs are generally avoided in React and should be used with precautions. It is because they DIRECTLY interact with the Real DOM and in React that is not desirable behaviour.

We can, however, use refs in the following situations.

  • Interaction with third party libraries like jQuery.
  • Doing animations
  • Managing focus when we move to a text box

There are many ways to use “refs” but we will see the way introduced in React 16.3 and that is by  using React.createRef()

In the example for Ref, we have an input box. When we CLICK on the submit button, we’ll read the value ENTERED by the user and log it to the console. The same thing we could have achieved by using normal state and setState also.

class RefTextInputDemo extends React.Component {  constructor(props) {    SUPER(props);    // create a ref to store the text Input element    this.inputNewItem = React.createRef();  }  handleClick = e => {    e.preventDefault();    console.log(this.inputNewItem.current.value);  };  render() {     // tell React that we will associate the <input> ref     // with the `inputNewItem` that was created in the constructor    return (      <div>        <form onSubmit={e => this.handleClick(e)}>          <input type="text" ref={this.inputNewItem} />          <button>Submit</button>        </form>      </div>    );  } }



Discussion

No Comment Found