Access DOM nodes and customize ref values.
Creates a ref object for class components. Returns object with .current property.
function createRef<T>(): RefObject<T>;
interface RefObject<T> {
readonly current: T | null;
}class TextInput extends Component {
inputRef = createRef();
focusInput = () => {
this.inputRef.current?.focus(); // Use optional chaining
};
render() {
return <input ref={this.inputRef} />;
}
}Forward ref to child component. Required to pass refs to function components.
function forwardRef<P, T>(
render: (props: P, ref: Ref<T>) => ReactElement | null
): ComponentType<P & { ref?: Ref<T> }>;
type Ref<T> = RefObject<T> | ((instance: T | null) => void) | null;const Input = forwardRef((props, ref) => {
return <input ref={ref} {...props} />;
});
// Parent uses ref
const inputRef = useRef(null);
<Input ref={inputRef} />
inputRef.current?.focus();
// With useImperativeHandle for custom API
const CustomInput = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus(),
clear: () => inputRef.current.value = ''
}));
return <input ref={inputRef} {...props} />;
});