How to Use Forward Ref In React
Sep 2023 · 11 min
Learn how to utilize the power of Forward Refs in React to manage DOM elements and enhance your component communication. This comprehensive guide provides clear examples and practical tips for implementing Forward Refs effectively in your React applications.

Introduction
In the world of React, understanding how things work under the hood is essential for building efficient and manageable applications. Before we dive into the magic of forwardRef, it’s important that you understand or have some knowledge of useRef in react. React's forwardRef is like a secret handshake that lets a parent component easily share a special connection with a child component. The connection I am talking about is a reference (ref) that is passed down from a parent component to a child component.
What are refs
To understand ref forwarding, we must first understand what refs are. Refs are a way to access and interact with a DOM element directly. Refs allow you to bypass the typical React data flow and perform actions not achievable with props and state alone.
Common Use Cases for Refs
Now that we have a grasp of what refs are, let's explore some common scenarios where they come in handy within React applications:
Accessing and Manipulating DOM Elements
Refs allow you to directly access and interact with DOM elements. This can be incredibly useful when integrating third-party libraries, performing animations, or working with interactive components.
Managing Focus
Controlling the focus within your application is crucial for accessibility and user experience. Refs make it straightforward to manage focus, especially in situations involving forms, modals, or dynamic UI elements.
Imperative Actions
There are times when you need to trigger imperative actions, like scrolling to a specific position, playing/pausing media, or triggering custom functions. Refs provide an elegant way to execute these actions.
Integrating with External Libraries
When your React application needs to interact with non-React libraries or integrate with existing codebases, refs act as a bridge, allowing seamless communication between React components and external scripts.
By understanding these practical use cases for refs, you're well-prepared to dive into the fascinating world of forwardRef. In the upcoming sections, we'll explore how forwardRef builds upon the concept of refs, enabling even more powerful interactions between parent and child components. Let's continue our journey!
Creating and Using Refs in React
Before we move on to more advanced concepts like forwardRef, it's important to understand how to create and use refs in React. Refs provide a straightforward way to access and interact with DOM elements or React components directly.
Creating a Ref
In React, you can create a ref using the useRef hook or by using the React.createRef() method. Here's how you can create a ref using useRef:
import React, { useRef } from 'react';
// Create a ref
const myRef = useRef(null);
Attaching a ref
Attaching refs in React is the process of relating a ref with a DOM element for direct DOM manipulation. This is a crucial step for utilizing refs in tasks like focus management, dimension measurement, and animations.
<div ref={myRef}>Hello, Ref!</div>
And, finally, when we are ready to access the DOM element later on the component lifecycle, we can do something like this:
myRef.current.style.color = 'blue';
Let’s see how it will look like a complete component
import React, { useRef } from 'react';
function MyComponent() {
const myRef = useRef();
const handleClick = () => {
// Access and manipulate the DOM element
myRef.current.style.color = 'blue';
};
return (
<div>
<button onClick={handleClick}>Change Color</button>
<div ref={myRef}>Hello, Ref!</div>
</div>
);
}
Understanding how to create and use refs is fundamental to working with forwardRef and other advanced React features. Now that you're equipped with this knowledge, let's explore forwardRef in more depth and discover its capabilities.
What is a forwardRef?
In its essence, forwardRef is a feature in React that allows a parent component to pass a ref down to a child component, enabling direct access to the child's DOM elements or React components. It's like handing over a magical key that unlocks hidden potential within your components.
In the sections that follow, we'll explore how to use forwardRef effectively, its benefits, and real-world scenarios where it shines. So, let's dive deeper into this exciting aspect of React development!
Using forwardRef: A Practical Guide
Now that we understand the use of forwardRef in React, let's roll up our sleeves and put this knowledge into action. In this section, we'll walk through practical examples of how to use forwardRef effectively.
At its core, using forwardRef involves two essential steps: creating a ref and forwarding it to a child component. We'll start with a basic example to illustrate this concept.
Creating a Parent Component with a ref
To get started with forwardRef, we'll begin by creating a parent component. Within this component, we'll set up a ref that will later be passed to the child component. Here's an example of the parent component code:
import React, { useRef, forwardRef } from 'react';
const ParentComponent = () => {
// Create a ref for the child component
const childRef = useRef();
// Define a function to handle changes
const handleClick = () => {
// Access and manipulate the child component's DOM element
childRef.current.style.color = 'blue';
};
return (
<div>
<button onClick={handleClick}>Change Color</button>
{/* Child component goes here */}
</div>
);
};
export default ParentComponent;
In this step, we've established the parent component and created a ref named childRef. We've also added a function handleClick to demonstrate how we can manipulate the child component's DOM element using this ref.
The next step will involve creating the child component and forwarding the ref to it.
Creating a Child Component and Forwarding the Ref
Now that we have our parent component with a ref in place, it's time to create the child component and forward the ref to it. This allows us to establish a direct connection between the parent and child components.
import React, { forwardRef } from 'react';
// Define the child component using forwardRef
const ChildComponent = forwardRef((props, ref) => {
// The ref is automatically passed as the second argument
// Use it to access and manipulate the child component's DOM element
return (
<div ref={ref}>
Child Component
</div>
);
});
export default ChildComponent;
In this step, we define the child component using forwardRef and this forwardRef takes a callback function that contains our child component. This special function accepts two arguments: props and ref. By using forwardRef, we automatically receive the ref passed from the parent component. Inside the child component, we attach this ref to the desired DOM element, enabling direct manipulation.
With this setup, the parent and child components are connected through the ref, allowing us to interact with the child's DOM element from the parent component.
Complete Code Example
import React, { useRef, forwardRef } from 'react';
// Step 1: Creating a Parent Component with a Ref
const ParentComponent = () => {
// Create a ref for the child component
const childRef = useRef();
// Function to handle changes in the child component
const handleClick = () => {
// Access and manipulate the child component's DOM element
childRef.current.style.color = 'blue';
};
return (
<div>
<button onClick={handleClick}>Change Color</button>
{/* Step 2: Rendering the Child Component and Passing the Ref */}
<ChildComponent ref={childRef} />
</div>
);
};
// Step 3: Creating a Child Component and Forwarding the Ref
const ChildComponent = forwardRef((props, ref) => {
// The ref is automatically passed as the second argument
// Use it to access and manipulate the child component's DOM element
return (
<div ref={ref}>
Child Component
</div>
);
});
export default ParentComponent;
In this example:
- Step 1: We create the parent component ParentComponent and set up a ref named childRef in it.
- The handleClick function demonstrates how we can manipulate the child component's DOM element using this ref.
- Step 2: Inside the parent component's JSX, we render the ChildComponent and pass the childRef as a ref prop.
- Step 3: The ChildComponent is defined using forwardRef, which automatically receives the ref passed from the parent component. Inside the child component, we attach this ref to the desired DOM element.
This code example demonstrates the complete process of creating a parent and child component, passing a ref from the parent to the child, and using it to manipulate the child component's DOM element.
When to Use forwardRef
- Accessing Child Component DOM Elements: Use forwardRef when you need to access and manipulate the DOM elements within a child component directly. It's ideal for scenarios like managing focus, styling, or triggering animations.
- Custom Input Components: Creating custom input components that encapsulate complex behavior and validation is a common use case for forwardRef. It keeps the interface clean for parent components while providing flexibility.
- Integrating with Third-Party Libraries: When integrating React with external libraries that require direct DOM manipulation, forwardRef simplifies the process. It allows you to create a React wrapper around the external library and manage the interaction seamlessly.
When Not to Use forwardRef
- Simple Data Passing: If you only need to pass data or props from a parent to a child component without direct DOM manipulation, there's usually no need to use forwardRef. Traditional props and state suffice for such scenarios.
- Overly Complex Components: Avoid using forwardRef in components that are becoming overly complex. If your component is trying to do too much, it's a sign that it might need refactoring.
Using forwardRef in TypeScript
Now, let's dive into a TypeScript example that demonstrates how to use forwardRef in a real-world scenario. In this example, we have a parent component, HeroSection, and a child component, Text. The goal is to create a reference to specific HTML elements within the child component from the parent component.
Example: Creating a Dynamic and Reusable Text Component with forwardRef in TypeScript
In this example, we will explore the creation of a dynamic and reusable text component that can render either h1, h2, or simple p (paragraph) elements based on a prop called as. Additionally, this custom text component will have the ability to receive a ref, making it a valuable real-world use case of forwardRef.
Parent Component - SectionTwo
We'll begin with the parent component, HeroSection, which creates a ref that can either reference a heading (h1 or h2) or a paragraph (p). The HeroSection component will then utilize the custom Text component, passing the ref to it.
// **Parent Component**
import React, { useEffect, useRef } from "react";
import Text from "@/ui/Text";
const HeroSection = () => {
// Create a ref to access specific HTML elements within the child component
const textOneRef = useRef<HTMLHeadingElement | HTMLParagraphElement | null>(
null
);
useEffect(() => {
// Log the ref to the console to demonstrate its usage
console.log("textOneRef", textOneRef);
}, [textOneRef]);
return (
<section className="h-screen w-full flex items-center justify-center flex-col gap-[154px]">
{/* Using the Text component and passing the ref */}
<Text as="h2" className="text-center" ref={textOneRef}>
Welcome to a new Start.
</Text>
{/* Additional Text component */}
</section>
);
};
export default HeroSection;
Child Component - Text
The child component, Text, is designed to be dynamic and versatile. It accepts a prop called as to determine whether to render an h1, h2, or p element. Additionally, it gracefully handles the ref passed from the parent component, showcasing the power of forwardRef.
// **Child Component**
import React, { forwardRef } from "react";
import { cn } from "@/lib/utils/twMerge";
interface Props {
children: React.ReactNode;
className?: string;
as?: string;
}
const Text = forwardRef<HTMLHeadingElement | HTMLParagraphElement, Props>(
(props, ref) => {
const { children, className, as } = props;
if (as === "h1") {
return (
<h1
ref={ref}
className={cn(
"font-bold text-[70px] leading-[84px] text-secondary tracking-[-5%]",
className
)}
>
{children}
</h1>
);
}
if (as === "h2") {
return (
<h2
ref={ref}
className={cn(
"font-medium text-[40px] leading-[48px] text-secondary tracking-[-5%] ",
className
)}
>
{children}
</h2>
);
}
return (
<p
ref={ref}
className={cn(
" text-accent text-[24px] font-normal leading-[28.8px] tracking-[-5%] ",
className
)}
>
{children}
</p>
);
}
);
export default Text;
In this example:
- The HeroSection, parent component creates a ref called textOneRef.
- The Text, child component, which uses forwardRef, accepts the ref passed from the parent component. It allows dynamic rendering based on the as prop, making it versatile.
- The parent component renders the Text component, passing the textOneRef ref to it.
- The useEffect in the parent component logs the ref to the console, demonstrating how you can access and manipulate specific HTML elements within the child component using forwardRef.
This TypeScript example illustrates how to use forwardRef in a practical scenario, enhancing your understanding of this powerful feature in React.
Conclusion: Mastering forwardRef in React
In this guide, we've walked into the world of forwardRef in React, from its fundamental concepts to practical implementation. Let's recap the key takeaways:
- Understanding Refs: We started by exploring what refs are and their practical use cases. Refs are powerful tools for direct DOM manipulation, focus management, and more.
- Introducing forwardRef: We then introduced forwardRef, a feature that allows parent components to pass refs to child components. It simplifies parent-child interactions and opens doors to more flexible components.
- Practical Implementation: We provided a step-by-step guide on how to create a parent component with a ref, create a child component using forwardRef, and pass and use the ref for direct manipulation.
- Best Practices: We discussed when to use forwardRef and when it might not be the best choice. Following best practices ensures that you leverage forwardRef effectively in your projects.
"With this knowledge in hand, you're now ready to create React components that are not only efficient and maintainable but also flexible and interactive. forwardRef is a powerful tool that enhances your development capabilities, and by using it wisely, you can elevate your React applications to the next level.
I hope this guide has equipped you with the skills and insights needed to excel in your React development journey. Happy coding!"