Ref forwarding is a technique for automatically passing a ref through a component to one of its children. This is typically not necessary for most components in the application. However, it can be useful for some kinds of components, especially in reusable component libraries. The most common scenarios are described below.
import React, { createRef, forwardRef, ChangeEventHandler } from 'react';
type InputComponentProps = {
value?: string;
onChange?: ChangeEventHandler;
};
type InputRefType = HTMLInputElement;
const InputComponent = forwardRef<InputRefType, InputComponentProps>(
({ value, onChange }, ref) => (
<input ref={ref} value={value} onChange={onChange} />
),
);
const SmallForm = (): JSX.Element => {
const inputRef = createRef<InputRefType>();
const onButtonClick = () => {
inputRef.current?.focus();
};
return (
<>
<button type="button" onClick={onButtonClick}>
Focus to input
</button>
<InputComponent ref={inputRef} />
</>
);
};
Here is a step-by-step explanation of what happens in the above example:
- We create a React ref by calling
createRefand assign it to arefvariable withInputRefTypetype. - We pass our
refdown to<InputComponent ref={ref}>by specifying it as a JSX attribute. - React passes the
refto the(props, ref) => ...function insideforwardRefas a second argument. - We forward this
refargument down to<input ref={ref}>by specifying it as a JSX attribute. - When the
refis attached,ref.currentwill point to the<input>DOM node.