React Refs are React’s abbreviation for references. Similar to buttons in React. This is an attribute that can be used to store a reference to a specific DOM node or React element. Provides a way to access and interact with React DOM nodes or React elements. Use this option if you want to change the value of child components without using props.
The React team provided an escape hatch, keeping the library open not only for situations where the model might not work but for situations beyond what they specifically designed.
These escape hatches are references that allow direct access to DOM properties. React typically uses the state to update data on the screen by re-rendering components. However, there are certain situations where you need to deal directly with DOM properties, and that’s where arbiters come in.
This article explores why React, a framework designed to abstract code from DOM manipulation, leaves the door open for developer access.
When to Use React Refs
- When we need DOM measurements such as managing focus, text selection, or media playback.
- It is used in triggering imperative animations.
- When integrating with third-party DOM libraries.
- It can also use as in callbacks.
When to Not use React Refs
- Its use should be avoided for anything that can be done declaratively. For example, instead of using open() and close() methods on a Dialog component, you need to pass an isOpen prop to it.
- You should have to avoid overuse of the Refs.
How to Create Refs
React provides createRef(). You can create a reference using this method. Next, we need to attach the create link to the react element. This can be done with the ref attribute. For functional components, you should also use the useRef() hook with an initial value of null. In most cases, you should assign a reference to an instance property. This is done when the component is created so that it can be referenced within the component.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.callRef = React.createRef();
}
render() {
return <div ref={this.callRef} />;
}
}
How to Acces Refs
We can access the reference to the node by passing a ref to an element in the render, which will then be accessible at the current attribute of the ref.
const node = this.callRef.current;
Based on the type of node, the ref has different values. For example, if an HTML element uses the ref attribute, the ref in the createRef() constructor will get the DOM element as the “current” property. Also, if you use the ref attribute on a custom class component, in this case, the “current” of the ref object will contain the mounted instance of the component. Also, function components don’t have instances, so you can’t use the ref attribute. Let’s look at each of these cases separately.
Refs Current Properties
- When the ref attribute is used in HTML element, the ref created with React.createRef() receives the underlying DOM element as its current property.
- If the ref attribute is used on a custom class component, then ref object receives the mounted instance of the component as its current property.
- The ref attribute cannot be used on function components because they don’t have instances.
Add Ref to DOM elements
To add a reference to a DOM element, we need to pass the ref attribute. In this case, the “current” property is assigned to the DOM element when the component is deployed. React reassigns the “current” property to null when the DOM element is detached. And this reference update happens before the componentDidMount and componentDidUpdate lifecycles. The following example shows how to add a link to a DOM element.
class myComponent extends Component {
constructor(props) {
super(props);
this.refInput = React.createRef(); //create ref
this.focusInputText = this.focusInputText.bind(this); //to bind this keyword
}
focusInputText() {
this.refInput.current.focus(); // to focus input using DOM API
}
render() {
return (
<div>
{/* To associate the refInput in constructor with <input> */}
<input type="text" ref={this.refInput} />
<input type="button" value="Click to Focus input" onClick={this.focusInputText} />
</div>
);
}
}
Add Ref to Class components
Only when we are using a class component, if we want to simulate that the refInput is clicked just after mounting, then in this case, we can call the focusInputText method manually and use the ref to get access to the myComponent.
class AutoFocusComp extends Component {
constructor(props) {
super(props);
this.refInput = React.createRef(); //create ref
}
componentDidMount() {
this.refInput.current.focusInputText(); //manually call focusInputText method
}
render() {
//to associate the ref with our component
return (
<myComponent ref={this.refInput} />
);
}
}
Ref with Functional Component
We know that functional components don’t have instances, so we can’t apply the ref attribute directly to functional components. So if you use ref, you should use forwardRef. Otherwise, this component should be cast to class component. However, if you just want to reference a DOM element or class component inside a function component, you can use the ref attribute.
function useRefExample() {
const inputRef= useRef(null);
const onButtonClick = () => {
inputRef.current.focus();
};
return (
<>
<input ref={inputRef} type="text" />
<button onClick={onButtonClick}>Submit</button>
</>
);
}
Callback Refs
In react, there is another way to use refs that is called “callback refs” and it gives more control when the refs are set and unset. Instead of creating refs by createRef() method, React allows a way to create refs by passing a callback function to the ref attribute of a component. It looks like the below code.
this.callRefInput = element} />
The callback function is used to store a reference to the DOM node in an instance property and can be accessed elsewhere. It can be accessed as below:
this.callRefInput.value
React with useRef()
Introduced in React 16.7 and later. Useful for accessing and manipulating DOM nodes or elements. B. Target an input element or access the value of an input element. Returns a ref object with the .current property initialized with the passed arguments. The returned object will live for the life of the component.
Syntax
const refContainer = useRef(initialValue);
Example
function useRefExample() {
const inputRef= useRef(null);
const onButtonClick = () => {
inputRef.current.focus();
};
return (
<>
Submit
);
}
Also read | React Keys | How to use React Keys