Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you set the Typescript type for useRef hook in React Native?

How do I correctly type the useRef for a React Native TextInput?
With the below code I get the following error.

Property 'isFocused' does not exist on type 'MutableRefObject<TextInput>'

import React, { useRef } from 'react';
import { TextInput } from 'react-native';

const TestScreen = () => {

  const searchInputRef = useRef<TextInput>();

  const updateSearchText = (searchText: string) => {
    console.log(searchTextRef.isFocused()); //  👈 Error here.
  };

  return (
    <TextInput
      ref={searchInputRef}
      placeholder="Search"
      onChangeText={(text: string) => updateSearchText(text)}
      autoCorrect={false}
      autoCapitalize="none"
      value={searchText}
    />
  )

}
like image 963
GollyJer Avatar asked Dec 16 '19 04:12

GollyJer


People also ask

How do I use useRef in React native TypeScript?

To use useRef with TypeScript, it is actually pretty easy, all you need to do is provide the type that you want to the function via open and closed chevrons like you would with other React hooks like so: const myRef = useRef<number>(0) .

How do I use useRef hook in React native?

Use useRef to track application renders. useRef() only returns one item. It returns an Object called current . When we initialize useRef we set the initial value: useRef(0) .

How do you use set types on React useState with TypeScript?

To type the useState hook as an object in React, use the hook's generic, e.g. const [employee, setEmployee] = useState<{name: string; salary: number}>({name: '',salary: 0}) . The state variable will only accept key-value pairs of the specified type.

How do you use useRef in React for input?

To make it work you'll need to create a reference to the input, assign the reference to ref attribute of the tag, and after mounting call the special method element. focus() on the element. Try the demo. const inputRef = useRef() creates a reference to hold the input element.


1 Answers

It should be

 const updateSearchText = (searchText: string) => {
    console.log(searchInputRef.current.isFocused());
  };

like image 68
Tuan Luong Avatar answered Oct 05 '22 17:10

Tuan Luong