Refs provide way to access react elements created in the render() method.
In typical react dataflow, we generally pass information/data from parent to child components using props.
However, there are cases when we need to modify the child component outside the typical dataflow. So we could use Refs for these cases.
Creating Refs:
class InLineEdit extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); } render() { return <div ref={this.myRef} ></div>; }}
class InLineEdit extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} ></div>;
Accessing Refs:
const ref = this.myRef.current;
Being said that Refs should be avoided and we should do things in a React way i.e props.
The ref is used to return a reference to the element. They should be avoided in most cases, however, they can be useful when we need direct access to DOM element or an instance of a component.