Basic forwardRef Pattern
What you'll learn: How to wrap a custom component with forwardRef so it can receive and attach a ref to its internal DOM element.
By default, custom components don't accept the ref prop—React reserves it for built-in elements like <input> or <div>. If you try passing a ref to <MyInput />, React will warn you and the ref won't work.
forwardRef solves this by wrapping your component in a special function that receives ref as a second parameter (after props). You can then attach that ref to a DOM element inside your component.
How It Works
Here's the pattern:
import { forwardRef } from 'react';
const MyInput = forwardRef((props, ref) => {
return <input ref={ref} {...props} />;
});
Now parent components can pass a ref and access the underlying <input>:
function Form() {
const inputRef = useRef(null);
function handleClick() {
inputRef.current.focus(); // Works!
}
return (
<>
<MyInput ref={inputRef} />
<button onClick={handleClick}>Focus Input</button>
</>
);
}
The Anatomy
- Wrap your component with
forwardRef() - Accept
refas the second parameter (afterprops) - Attach
refto the actual DOM element inside your JSX
Think of it like a relay race: the parent hands the ref baton to your component, and your component passes it along to the real DOM element.
Key Takeaway: Use forwardRef to create custom components that expose their internal DOM nodes through the ref prop, enabling parent components to interact directly with those elements.