What is `forwardRef()` in React used for?
TL;DR
forwardRef()
in React is used to pass a ref through a component to one of its child components. This is useful when you need to access a DOM element or a child component's instance directly from a parent component. You wrap your functional component with forwardRef()
and use the ref
parameter to forward the ref to the desired child element.
What is forwardRef()
in React used for?
Introduction
In React, forwardRef()
is a higher-order function that allows you to forward a ref through a component to one of its child components. This is particularly useful when you need to access a DOM element or a child component's instance directly from a parent component.
Why use forwardRef()
?
There are several scenarios where forwardRef()
is beneficial:
- Accessing DOM elements: When you need to manipulate a DOM element directly, such as focusing an input field.
- Interacting with child components: When you need to call methods or access properties of a child component instance.
How to use forwardRef()
To use forwardRef()
, you wrap your functional component with it and use the ref
parameter to forward the ref to the desired child element.
Example
Here is a simple example demonstrating how to use forwardRef()
:
In this example:
MyInput
is a functional component wrapped withforwardRef()
.- The
ref
parameter is forwarded to theinput
element insideMyInput
. - In
ParentComponent
, a ref (inputRef
) is created usinguseRef()
. - The
inputRef
is passed toMyInput
, allowing the parent component to access the input element directly. - The
focusInput
function uses the ref to focus the input element when the button is clicked.
Important considerations
- Functional components only:
forwardRef()
is used with functional components. Class components can directly use refs withoutforwardRef()
. - Ref forwarding: Ensure that the ref is forwarded to a DOM element or a class component instance, not another functional component.