Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript issues when creating ref for React Native TextInput

I came across an issue when defining refs i.e.

inputRef = React.createRef(null)

//...

const someFunction () => {
 if (this.inputRef && this.inputRef.current) {
   this.inputRef.current.focus()
 }
}

//...

<TextInput ref={inputRef} />

When I access .focus() I get following error:

[ts] Property 'focus' does not exist on type 'never'. [2339]

Can I somehow tell createRef that this ref can be null or TextInput so it knows that .focus() may exist?

like image 960
Ilja Avatar asked Nov 20 '18 10:11

Ilja


People also ask

What is ref in TextInput react native?

ref attribute on TextInput is used to store a reference to a DOM node. React will call the ref callback with the DOM element when the component mounts, and call it with null when it unmounts.


1 Answers

You can try the following:

inputRef = React.createRef<TextInput>();
like image 109
Peter Ambruzs Avatar answered Oct 11 '22 02:10

Peter Ambruzs