React forwardRef
🔁 React forwardRef (Complete Guide with Examples)
forwardRef is a special React function that allows you to pass a ref from a parent component to a child component. Normally, refs only work on DOM elements or class components — not functional components.
So forwardRef becomes useful when:
-
You want to access a DOM element inside a child component
-
You want a reusable input component with ref support
-
You need to control focus, scroll, play/pause from parent
🧠 Why do we need forwardRef?
Without forwardRef, this will NOT work:
React will warn:
“Function components cannot be given refs.”
So we wrap the component in forwardRef.
✅ Basic Example of forwardRef
Using it in a parent:
🔹 Clicking the button focuses the input — thanks to forwardRef.
🎯 Passing Refs + Props Together
You can still use props normally:
🧩 With useImperativeHandle (Advanced)
Sometimes you want to expose custom functionality rather than direct DOM access.
Example: A custom input component exposing a method:
Parent:
✔ Now the parent can call a custom function, instead of accessing the DOM directly — great for reusable components.
📌 When to Use forwardRef
| Case | Use? |
|---|---|
| Custom form input components | ✔ Yes |
| Reusable design system (buttons, fields) | ✔ Yes |
| Accessing DOM elements inside child | ✔ Yes |
| Normal parent-child communication | ❌ Not needed |
| Passing data via props | ❌ Use normal props |
🏁 Summary
| Feature | Supported by forwardRef |
|---|---|
| Access DOM inside child | ✔ |
| Support refs in functional components | ✔ |
Add custom API (useImperativeHandle) |
✔ |
| Replace props | ❌ |
