-1

What is the use case if ref in react when the same thing can be achieved with document.querySelector as well?

Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
Nishant Srivastava
  • 449
  • 2
  • 7
  • 18

1 Answers1

1

document.querySelector() cannot fulfill the purpose of refs. Because refs are used to target the React Component while document.querySelector() returns HTML Element Consider this example.

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
       childid:"someid"
    }
  }
  render() {
    return <Child ref={this.myRef} id={this.state.childid} />;
  }
}

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = { 
       data:"something"
    }
  }
  render() {
    return <div id={this.props.id}/>;
  }
}

In above code you can get the <div> using document.querySelector() in parent element. But you cannot get the <Child/> component inside parent. Without refs you couldn't are unable access the data in state of Child

Maheer Ali
  • 35,834
  • 5
  • 42
  • 73