I am working on a react-native app in which I am facing a problem with the TextInput.
Whenever I press a key on the keyboard, the keyboard closes down.
I have tried using different text input components like material text input and 'react-native-elements' input. However the same issue exists.
There are similar questions on stackexchange but they are all trying to fix this problem in TextInput. However, the problem is not in the TextInput but somewhere in the implementation of TextInput.
I have simplified the code to:
import React, {useState} from 'react';
import { Text, View, StyleSheet, TextInput } from 'react-native';
const App = () => {
const [additionalComments, setAdditionalComments] = useState("");
const StarFeedback = () => {
return (
<TextInput
placeholder="Additional Comments"
onChangeText={text => setAdditionalComments(text)}
value={additionalComments}
/>
)
}
return (
<View>
<StarFeedback/>
</View>
);
};
export default App;
const styles = StyleSheet.create({
});
Link to snack: https://snack.expo.dev/@rachitkohli/634602
CodePudding user response:
You shouldn't use the value
attribute on each input. It's better (less re-renders) to use a useRef
and make use the onEndEditing
to store the value.
import React, {useState, useRef, useCallback } from 'react';
import { Text, View, StyleSheet, TextInput, } from 'react-native';
const App = () => {
const [additionalComments, setAdditionalComments] = useState("");
const inputEl = useRef(null);
const handleInputSubmit = useCallback((ev) => {
const input = ev.nativeEvent.text;
// validate all you want here
setAdditionalComments(input)
}, [setAdditionalComments]);
const Aux = () => {
return (
<View style={{marginTop: 100}}>
<TextInput
ref={ inputEl }
placeholder="Additional Comments"
onEndEditing={ handleInputSubmit }
defaultValue={additionalComments}
/>
</View>
)
}
...
This way the component will only be update WHEN the user finishes the input.
You could use the onChange
to show a warning label for example (or for pre-fetching a search result, etc). But it's not worth to set a state on each key input.
CodePudding user response:
import React, {useState, useCallback} from 'react';
import { Text, View, StyleSheet, TextInput } from 'react-native';
const Aux = () => {
const [additionalComments, setAdditionalComments] = useState("");
const handleAdditionalCommentsChanged = (text) => {
setAdditionalComments(text);
};
return (
<View >
<TextInput
placeholder="Additional Comments"
onChangeText={handleAdditionalCommentsChanged}
value={additionalComments}
/>
</View>
)
}
const App = () => {
return (
<View>
<Aux/>
</View>
);
};
export default App;
Aux
component is declared inside App
component and additionalComments
is state of App
component, so it is getting refreshed every time as the prop passed to it is changing.