I'm trying to get a TextInput to gain focus on a button click but the TextInput is inside a custom component. I can get it to work if the TextInput is not inside a custom component and I found a couple answer for inside a custom component but not when using hooks.
When I try this way, I get the error: Uncaught TypeError: usernameTextInput.current is null
.
Screen A:
import React, { useRef } from 'react';
import { Pressable, Text } from "react-native";
import MyTextInput from "../components/MyTextInput";
const ScreenA = () => {
const refTextInput = useRef(null);
return (
<MyTextInput
ref={refTextInput}
...
/>
<Pressable onPress={() => refTextInput.current.focus()}>
<Text>Focus</Text>
</Pressable>
);
};
export default ScreenA;
MyTextInput Component:
import { TextInput } from "react-native";
const MyTextInput = (props) => {
return (
<TextInput
ref={props.ref}
...
/>
);
};
export default MyTextInput;
If I replace <MyInputText/>
with <InputText/>
then it focuses. How to I properly pass the focus request to my custom component?
CodePudding user response:
For that you have to use "forwarding ref" concept:
try below code:
Screen A:
import React, { useRef } from "react";
import { Pressable, SafeAreaView, Text, View } from "react-native";
import MyTextInput from "./components/MyTextInput";
const App = () => {
const refTextInput = React.createRef(null);
return (
<SafeAreaView>
<MyTextInput ref={refTextInput} />
<Pressable onPress={() => refTextInput.current.focus()}>
<Text>Focus</Text>
</Pressable>
</SafeAreaView>
);
};
export default App;
MyTextInput Component:
import { TextInput } from "react-native";
import React from "react";
const MyTextInput = React.forwardRef((props, ref) => {
return <TextInput ref={ref} />;
});
export default MyTextInput;
For "forwarding ref" concept you can refer to this doc: https://reactjs.org/docs/forwarding-refs.html