Callback Refs in React

Sumit kumar Singh
Web Development with sumit

--

Referring to components or elements in React is a common requirement, whether it’s to access their properties, trigger methods, or perform other operations. React provides two types of refs: string refs and callback refs. While string refs are simpler and commonly used, callback refs offer more control and flexibility.

What are Callback Refs?

Callback refs are a way to set a ref to a function instead of directly to a DOM element. This function is called with the component instance or DOM element as its argument when the component is mounted or updated. Callback refs are often used when you need to access properties or methods of a component or element that are not accessible through props.

Now, let’s explore callback refs with examples in both functional and class components.

Functional Component Example:

Here’s an example of using callback refs in a functional component:

import React, { useRef } from "react";

function MyComponent() {
const myRef = useRef(null);

const handleClick = () => {
myRef.current.focus();
};

return (
<>
<input type="text" ref={myRef} />
<button onClick={handleClick}>Focus input</button>
</>
);
}

In this example, we import the useRef hook from React, which allows us to create a mutable ref. Inside the MyComponent functional component, we declare a ref called myRef using useRef(null) and initialize it with null.

We then create a handleClick function that will be triggered when the button is clicked. Inside this function, we access the current property of the myRef object and call the focus method on it. This focuses on the input element, making it ready to accept user input.

To associate the ref with the input element, we pass myRef to the ref the attribute of the input. This allows us to reference the input element elsewhere in the component using myRef.current.

Class Component Example:

Callback refs can also be used with class components. Here’s an example:

import React from "react";

class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = null;
}

handleClick = () => {
this.myRef.focus();
};

setRef = (ref) => {
this.myRef = ref;
};

render() {
return (
<>
<input type="text" ref={this.setRef} />
<button onClick={this.handleClick}>Focus input</button>
</>
);
}
}

In this example, we define a class component MyComponent that extends the React.Component class. Inside the constructor, we initialize this.myRef to null.

We define a handleClick method that is triggered when the button is clicked. Inside this method, we call the focus method on this.myRef, which focuses on the input element.

Additionally, we define a setRef method that receives a ref as an argument. Inside this method, we set this.myRef to the received ref. We pass this method as the value of the ref attribute in the input element, associating the input with this.myRef.

When to Use Callback Refs?

Callback refs are particularly useful when you need to access properties or methods that are not directly available through props. They give you the ability to interact with the underlying DOM elements or component instances directly.

Here are some scenarios where callback refs can be beneficial:

  1. Focusing an Input Element: As shown in the examples above, callback refs can be used to focus an input element programmatically. This is especially useful when you want to trigger the focus behaviour from a button click or other events.
  2. Measuring DOM Element Dimensions: If you need to determine the dimensions of a DOM element, such as its width or height, you can utilize callback refs. By accessing the getBoundingClientRect method of the DOM element, you can obtain its dimensions and perform calculations accordingly.

Let’s see an example of measuring dimensions using callback refs:

import React, { useRef, useEffect, useState } from "react";

function MyComponent() {
const myRef = useRef(null);
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });

useEffect(() => {
if (myRef.current) {
const { width, height } = myRef.current.getBoundingClientRect();
setDimensions({ width, height });
}
}, []);

return (
<div ref={myRef}>
This element is {dimensions.width} pixels wide and {dimensions.height} pixels tall.
</div>
);
}

In this example, we create a state variable dimensions to store the width and height of the element. We use the useEffect hook with an empty dependency array to ensure it runs only once after the component is mounted.

Inside the effect, we check if myRef.current exists to ensure the ref is available. We then access the getBoundingClientRect method of the element through myRef.current and destructure its width and height properties. These values are used to update the dimensions state, triggering a re-render that displays the dimensions in the text of the div element.

3. Accessing Methods of Class Components: Callback refs can be used to access methods of class components. This is useful when you need to trigger specific actions or behaviours defined within the component.

4. Integrating with Third-Party Libraries: Callback refs can come in handy when integrating React with third-party libraries that require direct access to the underlying DOM elements.

In summary, callback refs in React provide a flexible way to access and manipulate components or DOM elements. They allow you to interact with properties, trigger methods, measure dimensions, and integrate with third-party libraries. Whether you’re working with functional components or class components, callback refs offer the control and flexibility needed to enhance your React applications.

Thanks for reading!

I hope you found this article useful. If you have any questions or suggestions, please leave comments. Your feedback helps me to become better.

Don’t forget to subscribe⭐️

Facebook Page: https://www.facebook.com/designTechWorld1

Instagram Page: https://www.instagram.com/techd.esign/

Youtube Channel: https://www.youtube.com/@tech..Design/

Twitter: https://twitter.com/sumit_singh2311

Gear used:

Laptop: https://amzn.to/3yKkzaC

Watch: https://amzn.to/41cialm

You can prefer React Book: https://amzn.to/3Tw29nx

Some extra books related to programing language:

https://amzn.to/3z3tW5s

https://amzn.to/40n4m6O

https://amzn.to/3Jzstse

https://amzn.to/3nbl8aE

*Important Disclaimer — “Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

--

--

Sumit kumar Singh
Web Development with sumit

YouTube: https://www.youtube.com/@tech..Design/ 📚 HTML,Angular, React,and JavaScript 🧑‍💻 Tips & tricks on Web Developing 👉 FULL STACK DEVELOPER