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}
/>
)
}
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) .
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) .
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.
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.
It should be
const updateSearchText = (searchText: string) => {
console.log(searchInputRef.current.isFocused());
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With