Handling multiple inputs with a single onChangeText handler in react native
December 23, 2021
Handling multiple inputs with a single onchange handler in react native:
We can handle multiple inputs with a single onChange handler easily in React.js. You can use event.target.name and event.target.value to read the name and value for an input field.
How to do it in React.js:
For example, we can use useState hooks to define the initial hook:
const [values, setValues] = useState({firstName: "", lastName: ""});
And we can create two input fields to use the firstName and lastName of this state:
<input
value={values.firstName}
onChange={handleChange}
....
<input
value={values.lastName}
onChange={handleChange}
....
Note that we are calling handleChange function for onChange in both of these inputs. Inside handleChange, we can get an event object and find out which input is calling it:
const handleChange = (e) => {
setValues({
...values,
[e.target.name]: e.target.value,
});
};
That’s it. It gets the data from e.target.name and e.target.value and updates the state.
This is the easiest way to handle multiple input fields in Reactjs.
Using single onChangeText handler in React Native:
In react native, we have to use TextInput component to show a text input. This component provides a callback onChangeText, inside this callback handler, the text is passed.
We have to call the state change function inside this callback handler. We can create a common function to handle it from different TextInput components.
For example:
import React from 'react';
import { SafeAreaView, StyleSheet, TextInput } from 'react-native';
const UselessTextInput = () => {
const [values, setValues] = React.useState({ firstName: '', lastName: '' });
const handleChange = (name, value) => {
setValues({
...values,
[name]: value,
});
};
return (
<SafeAreaView>
<TextInput
style={styles.input}
onChangeText={(text) => handleChange('firstName', text)}
value={values.firstName}
/>
<TextInput
style={styles.input}
onChangeText={(text) => handleChange('lastName', text)}
value={values.lastName}
/>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
input: {
height: 40,
margin: 32,
borderWidth: 1,
padding: 10,
},
});
export default UselessTextInput;
Since we are not getting the name of the input, we have to pass the name to the handleChange method.
This is similar to what we did for React.js. The only difference is that we have to provide the name of the TextInput.