How to Create and Add React Refs?
How to Create Refs in ReactJS?
You can create Refs using React.createRef(). Refs can be assigned to React elements via the ref attribute. It is generally assigned to an instance property when a component is created, and then can be referenced throughout the component.
Example:
How to Access ReactJS Refs?
If you want to access a reference to the node, you need to use the current attribute of the ref. It is available when we pass a ref inside the render method.
This is how it is done.
const node = this.callRef.current;
The ref value differs according to the type of the node:
-
When the ref attribute is used in an HTML element, the underlying DOM element is received by the ref as its current property.
-
If you are using the ref attribute on a custom class component, the ref object will find the mounted instance of the component as its current property.
-
You cannot use the ref attribute on function components because they don't have any instances.
How to Add Ref to DOM Elements Using Class Components?
Let’s understand this with an example.
Adding Refs to Functional Components
Here’s how you can add Refs to a functional component:
Callback Refs in ReactJS
There’s one another way to set refs in React. It is called “callback refs”, a method that gives more controls over setting up of refs.
<input type="text" this.callRefInput = element} />
How is it done?
Instead of passing a ref attribute created by createRef()
, you need to pass a function. The function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere.
You can access it by:
this.callRefInput.value
Example of callback refs
In this example, React will call the "ref"
callback to store the reference to the input DOM element when the component mounts. It will call it with null when the component unmounts. The callback refs passed between components is the same as you can work with object refs, which is created with React.createRef()
.
It’s Quiz Time!
