React forwardRef in 2 Minutes
What is React forwardRef and how to use it…?
2 min readMar 8, 2022
Using ref in React is easy and I guess you already know how to do it:
const ref = useRef()useEffect(() => {
// Access div DOM here
}, [])return (
<div ref={ref}>
Click Me
</div>
)
Sometimes you want to access an inner node from the parent component. Say you have a custom component for your buttons called Button
:
export default function Button(props) {
const { children } = props
return (
<button className="btn">
{children}
</button>
)
}
There’s this case that you need to access the inner <button>
element from the parent component, like so:
function App() {
const ref = useRef()
useEffect(() => {
// I want to access the element DOM
// But I can't do it from outside the Button
}, [])
return (
<Button ref={ref}>
Click Me
</Button>
)
}
The problem is that ref
is a special property and it is NOT passed down to the component. This is where you will need React forwardRef. With the help of forwardRef function, you can pass the ref object down to the component and pass it to any DOM element you prefer. In other words, we expose the button DOM to the parent…