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:
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" />
}React.forwardRef lets a component receive a ref from its parent and pass it down to a DOM element or inner component. It is needed when the parent must directly access a child's DOM node — for example, to focus an input or measure an element.
React 19: forwardRef is legacy — ref is now a regular prop: function Input({ label, ref, ...props }) { ... }. For React 18 and earlier, use React.forwardRef:
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 uses the ref to programmatically focus the input
const LoginForm = () => {
const emailRef = useRef<HTMLInputElement>(null)
useEffect(() => {
emailRef.current?.focus()
}, [])
return <Input ref={emailRef} label="Email" type="email" />
}