0
What is forwardRef in React, and why is it used?
kallyani
easy
0completed
0
Answer
forwardRef enables a parent component to pass a ref down through a component to one of its child elements.
This makes it possible for the parent to directly access a DOM element or interact with a child component when needed.
Example Without forwardRef (Problem):
<input ref={inputRef} /> // works
<CustomInput ref={inputRef} /> // does NOT workExample With forwardRef:
import React, { forwardRef } from 'react';
const CustomInput = React.forwardRef((props, ref) => {
return <input ref={ref} {...props} />;
});Now the parent can control the input:
inputRef.current.focus();Common Use Cases
- Focusing an input programmatically
- Exposing DOM methods from child components
- Building reusable UI libraries
Click to Reveal Answer
Tap anywhere to see the solution
Revealed
Comments0