React Forward Ref
In React, sometimes you need to access a child component’s DOM node directly — for example, to focus an input field, trigger animations, or measure its size. Normally, props only allow passing data, not references to DOM nodes. This is where React Forward Ref comes in handy.
React Forward Ref allows you to pass a ref from a parent component to a child component, giving the parent direct access to the child’s DOM element.
What is React Forward Ref?
React.forwardRef is a React API that lets function components accept a ref from their parent. By default, function components don’t support ref like class components do.
Benefits:
- Access DOM nodes in child components
- Integrate with third-party libraries that need refs
- Control focus, animations, or measurements programmatically
Syntax:
const Child = React.forwardRef((props, ref) => {
return <input ref={ref} {...props} />;
});
props– Normal props passed from parentref– Forwarded reference from the parent component
Example: Focusing an Input Field
import React, { useRef } from "react";
const InputField = React.forwardRef((props, ref) => {
return <input ref={ref} placeholder="Type here..." />;
});
function App() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus(); // Focus the input field
};
return (
<div>
<h1>React Forward Ref Example</h1>
<InputField ref={inputRef} />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
export default App;
InputFieldis a functional component wrapped inReact.forwardRef.inputRefin the parent (App) points directly to the<input>element inside the child.- Clicking the button focuses the input field programmatically.
Forward Ref with Class Components
Class components naturally support refs:
class InputField extends React.Component {
render() {
return <input ref={this.props.forwardedRef} placeholder="Class input" />;
}
}
const ForwardedInput = React.forwardRef((props, ref) => {
return <InputField {...props} forwardedRef={ref} />;
});
Use Cases for Forward Ref
- Programmatically focusing inputs
- Scrolling to child components
- Integrating with third-party UI libraries
- Triggering animations or measuring size/position
Combining Forward Ref with Hooks
You can combine forwardRef with hooks like useImperativeHandle to expose specific methods to the parent.
import React, { useRef, forwardRef, useImperativeHandle } from "react";
const Child = forwardRef((props, ref) => {
const localRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
localRef.current.focus();
},
}));
return <input ref={localRef} placeholder="Controlled by parent" />;
});
function App() {
const childRef = useRef();
return (
<div>
<Child ref={childRef} />
<button onClick={() => childRef.current.focus()}>Focus Child Input</button>
</div>
);
}
export default App;
useImperativeHandleallows you to customize what is exposed to the parent via the ref.- Here, the parent can call
childRef.current.focus()without directly accessing the DOM node.
