What is the use case if ref
in react when the same thing can be achieved with document.querySelector
as well?
Asked
Active
Viewed 220 times
-1

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

Nishant Srivastava
- 449
- 2
- 7
- 18
-
Check this out https://reactjs.org/docs/refs-and-the-dom.html – Praveen Rao Chavan.G Mar 06 '19 at 07:02
-
Please go through this similar question https://stackoverflow.com/questions/37273876/reactjs-this-refs-vs-document-getelementbyid – Arun CM Mar 06 '19 at 07:03
1 Answers
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