React.forwardRef cho phép component nhận ref từ parent và forward xuống DOM element hoặc component con bên trong. Cần thiết khi muốn parent có thể trực tiếp access DOM node của child, ví dụ để focus input hay measure element.
React 19: forwardRef là legacy — ref giờ là prop thông thường: function Input({ label, ref, ...props }) { ... }. Với React 18 trở về trước, dùng React.forwardRef:
tsx
interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
label: string
}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ label, ...props }, ref) => (
<label>
{label}
<input ref={ref} {...props} />
</label>
)
)
Input.displayName = 'Input'
// Parent sử dụng ref để focus programmatically
const LoginForm = () => {
const emailRef = useRef<HTMLInputElement>(null)
useEffect(() => {
emailRef.current?.focus()
}, [])
return <Input ref={emailRef} label="Email" type="email" />
}