Reputation: 369
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.
Upvotes: 1
Views: 4891
Reputation: 682
Type guards remain in effect across function boundaries only when the guarded variables are considered constant. So use const
:
const el = inputRef.current
if (el) {
setTimeout(() => el.focus(), 0);
}
Check inside a function is OK too only if you do not care about setTimeout
extra call:
setTimeout(() => inputRef.current?.focus(), 0);
Upvotes: 2
Reputation: 371019
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)
Upvotes: 4