forwardRef
Pass ref down to a child component. This is mainly used in libraries with higher-order components that wrap other components. UsingforwardRef, there is an easy way to get a reference to the wrapped component instead of the wrapper itself.
Signature
ForwardRefRenderFunction<T, P>
required
A render function that receives props and a forwarded ref.
FunctionalComponent
A functional component that forwards refs to the inner component.
Usage
Basic Example
Forward a ref to a DOM element:With TypeScript
Type the ref and props correctly:Higher-Order Component
Forward refs through a HOC:Imperative Handle
Expose custom methods through the ref:Implementation Details
TheforwardRef implementation in Preact:
Key Features
- Ref Removal: The
refprop is removed from the props object passed to the render function - Symbol Marking: Sets
$$typeoftoSymbol.for('react.forward_ref')for React compatibility - Display Name: Automatically generates a display name for debugging
- MobX Compatibility: Includes special handling for
mobx-reactcompatibility
ForwardedRef Type
Theref parameter can be:
Best Practices
- Type Safety: Always type your refs in TypeScript for better IDE support
- Display Names: Set a
displayNameon your render function for better debugging - Null Checks: Always check if the ref exists before using it
- Documentation: Document what the ref exposes when using
useImperativeHandle