Design Converter
Education
Last updated on Feb 26, 2025
•5 mins read
Last updated on Feb 26, 2025
•5 mins read
Software Development Executive - I
Builds things that work. And if it doesn’t, he’ll fix it — with Neovim, of course.
Need to manage multiple refs in React but not sure where to start?
Working with several refs can get tricky, especially when dealing with elements that need direct access to the DOM. React offers different ways to handle this, including ref objects, ref callbacks, and ref forwarding.
Refs help with tasks like managing focus, measuring elements, or connecting with third-party libraries. This guide covers different techniques for handling React multiple refs in both functional and class components.
Let’s break it down step by step!
The ref attribute in React enables direct access to a DOM element or a component instance. React creates a ref object using the useRef hook in functional components or React.createRef()
in class components.
1import React, { useRef } from "react"; 2 3const InputFocus = () => { 4 const inputRef = useRef(null); 5 6 const handleClick = () => { 7 if (inputRef.current) { 8 inputRef.current.focus(); 9 } 10 }; 11 12 return ( 13 <div> 14 <input ref={inputRef} type="text" placeholder="Click the button to focus" /> 15 <button onClick={handleClick}>Focus Input</button> 16 </div> 17 ); 18}; 19 20export default InputFocus;
This example demonstrates an input ref where a button click focuses the input field. The useRef hook initializes with null, a common pattern when managing refs in functional components.
When handling multiple refs, developers often need to reference multiple elements within a component. React provides different ways to manage multiple refs efficiently, such as using an array of refs or an object to store refs dynamically.
To understand how multiple refs work, let's visualize the reference assignment process using a Mermaid diagram:
Flowchart of Assigning Multiple Refs Dynamically
This flow represents how a component initializes and assigns multiple refs dynamically, allowing manipulation of dom nodes without causing unnecessary re-renders.
One approach is storing refs in an array and updating them dynamically:
1import React, { useRef } from "react"; 2 3const MultipleRefsExample = () => { 4 const refs = useRef([]); 5 6 const handleClick = (index) => { 7 if (refs.current[index]) { 8 refs.current[index].focus(); 9 } 10 }; 11 12 return ( 13 <div> 14 {[0, 1, 2].map((_, index) => ( 15 <input key={index} ref={(el) => (refs.current[index] = el)} type="text" /> 16 ))} 17 <button onClick={() => handleClick(1)}>Focus Second Input</button> 18 </div> 19 ); 20}; 21 22export default MultipleRefsExample;
In this example:
• An array of refs (refs.current) is used to store references to multiple elements dynamically.
• Callback refs update the refs.current array when React creates each input field.
• The button triggers focus on the second input field.
React provides two main approaches for handling refs: ref objects and callback refs.
Callback refs offer more flexibility than ref objects, allowing direct updates when a component mounts or unmounts.
1import React, { useState } from "react"; 2 3const CallbackRefExample = () => { 4 const [inputElement, setInputElement] = useState(null); 5 6 const handleClick = () => { 7 if (inputElement) { 8 inputElement.focus(); 9 } 10 }; 11 12 return ( 13 <div> 14 <input ref={setInputElement} type="text" placeholder="Focus with button" /> 15 <button onClick={handleClick}>Focus Input</button> 16 </div> 17 ); 18}; 19 20export default CallbackRefExample;
This approach ensures that the ref updates dynamically instead of being static like a ref object.
When passing refs from a parent component to a child component, React provides ref forwarding.
1import React, { forwardRef, useRef } from "react"; 2 3const CustomInput = forwardRef((props, ref) => { 4 return <input ref={ref} type="text" {...props} />; 5}); 6 7const ParentComponent = () => { 8 const inputRef = useRef(null); 9 10 return ( 11 <div> 12 <CustomInput ref={inputRef} placeholder="This is forwarded ref" /> 13 <button onClick={() => inputRef.current.focus()}>Focus Input</button> 14 </div> 15 ); 16}; 17 18export default ParentComponent;
Ref forwarding allows a parent component to access a child component's DOM node, making it useful for reusable components.
Refs are particularly useful when a component mounts, allowing direct access to dom nodes for immediate actions. For example, managing focus when a component mounts is a common use case.
1import React, { useEffect, useRef } from "react"; 2 3const AutoFocusInput = () => { 4 const inputRef = useRef(null); 5 6 useEffect(() => { 7 if (inputRef.current) { 8 inputRef.current.focus(); 9 } 10 }, []); 11 12 return <input ref={inputRef} type="text" placeholder="Auto-focus on mount" />; 13}; 14 15export default AutoFocusInput;
This example highlights how refs can be used for managing focus as soon as the component renders.
While refs are powerful, overusing refs can lead to complex component structures. React docs recommend using refs only when necessary, as they do not trigger a re-render when updated.
• Accessing dom nodes without triggering a re-render
• Storing mutable values across renders
• Managing focus or input ref values
• Integrating with non-React libraries
React multiple refs help manage multiple elements in a component. Each method—ref attribute, callback refs, and ref forwarding—serves a different purpose. Choosing the right one depends on how you need to interact with the DOM.
React’s documentation suggests using refs only when necessary. Too many can add complexity. Understanding input refs, callback refs, and ref objects make handling functional components easier.
By applying these methods correctly, developers can improve control over elements and keep components organized.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.