To use the useRef
hook in React, we call it in our component to return a ref.
Then we can assign that to an element.
For instance, we write
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
to set the input’s ref
prop to the inputEl
ref which we created with useRef
.
Then we can access the input with inputEl.current
.
And we call focus
on it to focus on the input.