In my react typescript app I have this code:
const inputRef = React.useRef<HTMLInputElement>(null);
const onIconClick = () => {
if (inputRef.current) {
setTimeout(() => inputRef.current.focus(), 0);
}
};
Typescript highlights inputRef.current.focus() with text:
const inputRef: React.RefObject<HTMLInputElement>
Object is possibly 'null'.ts(2531)
But I do "null checking"...
I also tried this construction:
const inputRef = React.useRef<HTMLInputElement>(null) as MutableRefObject<HTMLDivElement>
But I got error when I tried to pass ref to child component.
CodePudding user response:
The ref may have changed in between your checking of if (inputRef.current) {
and the call to .focus()
. Either do
setTimeout(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, 0);
or, more concisely, use optional chaining.
setTimeout(() => {
inputRef.current?.focus();
}, 0)