I'm using React Native with TypeScript and I need to set the focus on an input if certain conditions are met:
const inputEl = React.useRef<TextInput>(null);
React.useEffect(() => {
if (isLast && inputEl && inputEl.current) {
inputEl.current.focus();
}
}, []);
return (
<View>
<TextInput
ref={inputEl}
/>
The code above works but I get a TypeScript error if I remove the inputEl.current
check:
React.useEffect(() => {
if (isLast && inputEl) {
inputEl.current.focus();
}
}, []);
TS2531: Object is possibly 'null'.
Why is this happening? I'm checking for the existence of inputEl
, so if it does exist wouldn't it always have a current
property?
Also is my code correct or should the type be specified as:
const inputEl: React.RefObject<TextInput> = React.useRef(null);