Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6211

TypeScript with React Native - why does useEffect require 'current' check?

$
0
0

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);

Viewing all articles
Browse latest Browse all 6211

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>