I want to create a form without using useState to control the inputs because I only need the inputs values when the user presses the button, so I want to access/know the input value at that time only. I also think that updating the screen after each text input is not a good practice.
Let's assume that we have the following structure:
const Home = () => {
// const [inputValue, setInputValue] = useState(""); => I want to avoid that
const inputRef = useRef<TextInput>(null);
return (
<View>
<TextInput
style={styles.input}
ref={inputRef}
// value={inputValue} => I want to avoid that
// onChangeText={(text) => setInputValue(text)} => I want to avoid that
/>
</View>
);
};
We all know that when we have one TextInput on screen, we can type in it, without specifying the value prop and onChangeText, that we would normally use useState for that.
What I want to do is simply access the text that was input, and I would use a ref for that using useRef hook, but the problem is that using useRef I have access to TextInput props but the value is undefined because I am not specifying that. Am I missing something or there is no way to do that without using a useState for defining a value and onChangeText?
CodePudding user response:
TextInput
by nature is a controlled component.
However, to reach the behavior you need, you can use onChangeText
to update the value wanted at the end:
<TextInput
ref={inputRef}
onChangeText={(text) => (inputRef.current.value = text)}
/>
I recommend applying best practices recommended for the component, or checking form libraries like react-hook-form
.
CodePudding user response:
Based on @Majed Badawi answer I could find the following solution.
const inputRef = useRef<TextInput>(null);
<TextInput
ref={inputRef}
onChangeText={(text) => (inputRef!.current!.context = text)}
/>
The !.
operator will make sure that nothing is null
, and the context
of the TextInput
is a readable property that you can set and read values.