forwardRef
- React course
- Intermediate
- Lesson 67/80
- 4 min
Learn to forward a ref to a child component with forwardRef.
forwardRef
Sometimes you need to pass a ref to a child component. For example, if you write an input component and the parent wants to focus that input, you need to forward the ref.
For this you use forwardRef. You wrap the component with forwardRef; it takes ref as a second parameter and attaches it to the relevant DOM element.
A ref is not a prop; it does not come inside props. forwardRef handles the ref specially.
Binding ref to DOM
A component wrapped with forwardRef takes ref as its second parameter. You bind this ref to a DOM element inside with ref={ref}.
The parent creates a ref with useRef and passes it to the child as ref={myRef}. The child receives it via forwardRef and binds it to the relevant DOM element. This way the parent can access the child's DOM node.
This pattern is common in design system components; the parent wants to focus the underlying input.
Practice FancyInput component
Complete the skeleton below. Write a FancyInput component with forwardRef; take (props, ref) and return <input ref={ref} {...props} />. Export it.
Starter code
import { forwardRef } from "react";
// Write the FancyInput component hereSample solution
import { forwardRef } from "react";
const FancyInput = forwardRef((props, ref) => {
return <input ref={ref} {...props} />;
});
export default FancyInput;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does forwardRef do?
- State iletir
- Ref iletir Correct answer
- Event yakalar
- Prop filtreler
Explanation: forwardRef forwards a ref to a child component.
2 forwardRef wrapping
const FancyInput = ____((props, ref) => {
return <input ref={ref} {...props} />;
});
const FancyInput = forwardRef((props, ref) => {
return <input ref={ref} {...props} />;
});
Explanation: forwardRef makes the component take a ref parameter.
3 forwardRef: match the terms
| Term | Meaning |
|---|---|
forwardRef |
Forwards the ref |
ref parameter |
Second argument |
ref={ref} |
Binds to the DOM |
useRef |
Creates a ref |