While writing React apps we are always following the component-based architecture but there might be a situation where you may have to manipulate or imperatively modify DOM element. So to accomplished this React provides something called as Refs. In simple terms, refs give access to the underlying DOM element.
As per the React documentation below are the best use cases of using refs:
- Managing focus, text selection, or media playback.
- Triggering imperative animations.
- Integrating with third-party DOM libraries.
Note: Avoid using refs everywhere into the app. If the things can be done using a declarative manner don't use refs.
In this article, we are going to see the different ways of creating refs in react along with some examples. So let's grab a cup of coffee and start coding.
TL;DR
So today we will be discussing three ways of creating refs in React.
- Callback Refs
- Using
React.creatRef()
API (from React 16.3) - Using useRef() hook
Callback Refs
As the name specifies, in callback refs we have to provide a callback function to ref props. So the function receives input as DOM element which we can store in a variable for further use in the application. For example, when a user clicks on the button the input element should have focus. First I am creating a component along with input and button.
import React, { Component } from "react";
class CallbackRefExample extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
Callback Ref Example:
<br />
<br />
<input type="text" />
<button style={{ margin: "8px" }}>Click</button>
</div>
);
}
}
export default CallbackRefExample;
I am dividing this into three steps:
First, create a callback function and bind this in the constructor. I have created a callback function called inputElementRef.
import React, { Component } from "react";
class CallbackRefExample extends Component {
constructor(props) {
super(props);
this.inputElementRef = this.inputElementRef.bind(this);
}
inputElementRef(inputElement) {
this.inputRef = inputElement;
}
render() {
return (
<div>
Callback Ref Example:
<br />
<br />
<input type="text" />
<button style={{ margin: "8px" }}>Click</button>
</div>
);
}
}
export default CallbackRefExample;
Second, assing inputElementRef()
function to ref props of an input element
<input type="text" ref={this.inputElementRef}/>
So we have now created our callback ref.
Third, create on click handler function to call the focus method using inputRef
.
handleClick(){
this.inputRef.focus();
}
and assign this function to the onClick
event of the button.
<button style={{ margin: "8px" }} onClick={this.handleClick} >Click</button>
So the final output looks likes:
Using React.createRef()
API
In 16.3 version of React has introduced a new API called React.createRef()
for creating refs. We don't need to create a callback function and assign it to ref props here. So just create a ref and stored it into some variable and assign this variable to ref prop of DOM element. So we will take the same example, create a functional component which has one input element and one button.
import React, { Component } from "react";
export default function CallbackRefExample() {
return (
<div>
Callback Ref Example:
<br />
<br />
<input type="text" />
<button style={{ margin: "8px" }}>Click</button>
</div>
);
}
Now create a variable called inputRef and assign it with React.createRef()
API.
let inputRef = React.createRef();
Now apply this inputRef to ref props of input element. After that create onClick handler for a button so that when button onClick event fire we have to focus the input element. So the final component looks like:
import React, { Component } from "react";
export default function CallbackRefExample() {
let inputRef = React.createRef();
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
Callback Ref Example:
<br />
<br />
<input type="text" ref={inputRef} />
<button style={{ margin: "8px" }} onClick={handleClick}>
Click
</button>
</div>
);
}
Here we will receive the mounted instance of the component in its current
property of ref. So that's why we have invoked focus()
function like
inputRef.current.focus();
Output:
Using useRef()
hook
We can now create a ref using hooks. So react provides us inbuilt hook called useRef()
. useRef hook is taking an initial value for the ref as input. So similar to React.createRef()
we have to create a variable which can store the ref reference for further use. Here is an example:
import React, { useRef } from "react";
export default function UseRefHookExample() {
let inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
useRef() hook Example:
<br />
<br />
<input type="text" ref={inputRef} />
<button style={{ margin: "8px" }} onClick={handleClick}>
Click
</button>
</div>
);
}
Output:
Conclusion
In this article, I have explained about different ways to create Refs in React JS and also created simple examples using ref.
I really hope that you enjoyed this article, and please do not hesitate to send me your thoughts or comments about what could I have done better.
You can follow me on twitter @sumitkharche01
Happy Coding!
Top comments (5)
I loved this article.
What you could do better is to add the language type to the code snippet, so it will automatically highlight some words. :D
like this
Thanks Henrique for your great feedback. I will keep in mind to add the language type to the code snippet in my next articles.
Hi sumit, please add the language type to this article also, it is difficult to read code without syntax highlighting...🙃
Thanks for feedback Jash. Added language type to this article.
Thanks, Sumit! Appreciate the efforts 🙂