React Forward Ref
Written By: Avinash Malhotra
Updated on
In React, refs let you directly access DOM elements or child components. But by default, refs can't be passed from parent to child — because props and refs work differently.
React Forward Ref allows you to pass refs to components in a way that enables components to receive and use refs from their parent components. In this way, we can directly access DOM elements or child components from their parent components.
Creating a Forward Ref
To create a forward ref, you use the forwardRef function from React. This function takes a render function as its argument and returns a React component.
Here is an example of how to use forwardRef:
import { useRef, forwardRef } from "react";
// Child Component
const InputBox = forwardRef((props, ref) => {
return <input ref={ref} type="text" placeholder="Type here..." />;
});
// Parent Component
function App() {
const inputRef = useRef();
const handleFocus = () => {
inputRef.current.focus();
};
return (
<div>
<InputBox ref={inputRef} />
<button onClick={handleFocus}>Focus Input</button>
</div>
);
}
Here's what happens:
- forwardRef allows the ref to be passed from App to InputBox.
- Inside InputBox, we attach it to the <input> element.
- When handleFocus runs, it focuses the input directly from the parent.
Using forwardRef with Custom Components
How to create forwardRef with custom components.
import { forwardRef } from "react";
const FancyInput = forwardRef(({ label }, ref) => {
return (
<div>
<label>{label}</label>
<input ref={ref} />
</div>
);
});
export default FancyInput;
Use it in a component
import { useRef } from "react";
import FancyInput from "./FancyInput";
function App() {
const inputRef = useRef();
return (
<div>
<FancyInput label="Enter Name:" ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus</button>
</div>
);
}
When to Use forwardRef
✅ Use it when:
- You need to expose a child's DOM element to its parent.
- You're building higher-order components (HOCs) that wrap other components.
- You want to create reusable component libraries that need to forward refs.
🚫 Don't use it when:
- You can pass data through props instead.
- The component doesn't directly need DOM access.
Summary
React Forward Ref is a powerful feature that allows you to pass refs from parent components to child components. This enables direct access to DOM elements or child component instances from their parents.
By using the forwardRef function, you can create components that can accept refs and attach them to specific elements within the component. This is especially useful for building higher-order components and reusable libraries.
Remember to use forwardRef judiciously — only when direct DOM access is necessary. In many cases, passing data through props is a cleaner solution.