TypeScript
/Advanced
React: forwardRef & Typing Refs
Definition
Using `React.forwardRef` to pass DOM refs down into custom child components, and properly typing the ref object using Generics.
Explain Like I'm New
Normally, you cannot pass a `ref` prop to a custom React component (like `<MyButton ref={btnRef} />`). React forces you to wrap the component in `forwardRef` to unlock it. However, wrapping it messes up TypeScript's understanding of the component, requiring very specific Generic types to fix.
Real World Example
Creating a reusable `FancyInput` component that needs to allow parent forms to call `.focus()` on the actual HTML input element buried inside it.
Common Use Cases
- •Reusable UI libraries
- •Focus management
- •Integration with D3/Chart.js
Interactive Example
Loading Code Playground...
Interview Questions
basic
- What two arguments does a `forwardRef` render function take?
intermediate
- When typing `React.forwardRef<T, P>`, what does `T` represent and what does `P` represent?
advanced
- How do you expose custom methods to a parent ref using `useImperativeHandle`?