Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use Ref when we can use querySelector?

I am new in the React world and was learning about Refs. The React doc says that:

Refs provide a way to access DOM nodes or React elements created in the render method.

I think that we can do the same thing with the querySelector function.
The React doc gives an example of how can we use Refs to focus on the input element.
Here's the code ->

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Doing the same thing with querySelector ->

class CustomTextInput extends React.Component {
constructor(props) {
    super(props);
    this.textInput = React.createRef();
  }

  focusTextInput = () => {
    const input = document.querySelector("input");
    input.focus();
  };

  render() {
    return (
      <div>
        <input type="text" ref={this.textInput} />
        <button type="button" onClick={this.focusTextInput}>
          Focus the Text Input
        </button>
      </div>
    );
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
like image 583
Yogesh Tripathi Avatar asked Jun 14 '20 18:06

Yogesh Tripathi


People also ask

Why might you use ref?

There are a few good use cases for refs: Managing focus, text selection, or media playback. Triggering imperative animations. Integrating with third-party DOM libraries.

What can I use instead of querySelector in React?

The equivalent of the document. querySelector() method in React is using refs. To select an element, set the ref prop on it to the return value of calling the useRef() hook and access the dom element using the current property on the ref , e.g. ref. current .

Is it OK to use querySelector in React?

Using querySelector in React is not incorrect and it won't break your functionality. However, it is preferred to use an approach provided by the React framework. Mostly because it comes with certain benefits and optimizations. Now that we know if we can use this method or not, let's see how to do it in React.

Why we should not use REF IN React?

It is a general rule of thumb to avoid using refs unless you absolutely have to. The official React documentation outlined only three possible use cases where refs are entirely considered useful for lack of better alternatives: Managing focus, text selection, or media playback. Triggering imperative animations.


1 Answers

Since, the framework itself has exposed a method to do something which can be done through vanilla javascript, it certainly has added advantages. One of the scenario I can think of is using React.forwardRef which can be used for:

  • Forwarding refs to DOM components
  • Forwarding refs in higher-order-components

As explained in the React docs itself:

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
like image 193
sonali Avatar answered Oct 27 '22 19:10

sonali