Home > Mobile >  How do I manage multiple user inputs with only one onChange in React Native?
How do I manage multiple user inputs with only one onChange in React Native?

Time:12-23

How do I handle multiple text inputs with only one onChange on React Native? For example: Name, age, nationality, eye color.

Additionally, how do I save all of the inputs with only one button? (I want to output a list with all of these inputs in the same "item")

CodePudding user response:

You can manage all states in an object. For example:

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  TextInput,
  Button,
  Alert,
} from 'react-native';

const UselessTextInput = () => {
  const [user, setUserData] = React.useState({ name: '', age: 0 });

  return (
    <SafeAreaView>
      <TextInput
        style={styles.input}
        onChangeText={(text) => setUserData({...user, name: text })}
        value={user.name}
      />
      <TextInput
        style={styles.input}
        onChangeText={(age) => setUserData({...user, age: age })}
        value={user.age}
      />
      <Button onPress={() => Alert.alert(`User name ${user.name}, age ${user.age}`)} title="click me" />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  input: {
    height: 40,
    marginTop: 42,
    borderWidth: 1,
    padding: 10,
  },
});

export default UselessTextInput;

CodePudding user response:

create a new function and make changes to the a copied object and push the new object to the state

const handleChange=(key,value)=>{
  const myState = user
  myState[key] = value
  setUserData(myState)
}

then pass the function call to onChangeText prop

    <TextInput
      style={styles.input}
      onChangeText={(text) => handleChange('name', text)}
      value={user.name}
    />
  • Related