If I change text of TextInput then I change useState named name
and setName
.
const [name, setName] = useState("")
<TextInput
defaultValue={meData?.me?.name}
onChangeText={(text) => setNameValue(text)}
/>
And I want to change disableConfirm state from true to first, if I change just one word in this TextInput with useEffect
.
const [disableConfirm, setDisableConfirm] = useState(true);
useEffect(() => {
setDisableConfirm(false)
}, [nameValue]);
The problem is when screen is first rendered, this useEffect is executed.
So disableConfirm state becomes false
even though I don't change any word in TextInput.
How to prevent first rendering here? how to detect only change of TextInput?
CodePudding user response:
Another way to achieve this would be using the TextInput
as a controlled component.
- First, create a state with a default value.
- Look for changes in that state variable, if it changes from what it was originally, then enable the submit button.
Snack Implementation for the same is here
Approach:
Declare a state
variable with a default value
const [name, setName] = React.useState(SOME_DEFAULT_VALUE);
Now for the TextInput
, what you can do is
<TextInput placeholder="Enter Name" onChangeText={setName} value={name} />
What this does is, it updates the field with the name
variable every time you type something in it.
Now, to look for the changes, what you can do is,
useEffect(() => {
if (name !== SOME_DEFAULT_VALUE) {
setDisableConfirm(false);
} else {
/*
You can disable the button here
If you want user to change the textinput value
atleast once from what it was originally,
for that set disableConfirm to false here
*/
}
}, [name]);