Search code examples
react-nativereact-native-elements

Input text inside a map function does not change react native


I have problem with input text when I try to change it return to previous value was working fine out side map func. but inside it refuse to change it value. I think it re render itself on change text. so how do I change text and save name

userdata.map((l, i) => (
                    <Input label='First Name' value={l.name}
                      onChangeText={setname} /> 
<Button title="Modify" onPress={() => 
                    modifyDetails(
                      name,
                      )
                    } />
))

Edit: Based on Mohammad code I have done this

<Modal
        animationType="slide"
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => {
          Alert.alert("Modal has been closed.");
        }}
      >
        <ScrollView>
          <View style={styles.centeredView}>
            <View style={styles.modalView}>
              <TouchableHighlight
                  onPress={() => {
                    setModalVisible(!modalVisible);
                  }}
                >
                    <Text style={styles.textStyleClose}>X</Text>
                </TouchableHighlight>
                   <UserDataWithCallback/> // inputs called here
            </View>
          </View>
        </ScrollView>
</Modal>

But now renders empty inputs. Any solution.


Solution

  • useCallback will solve your problem.\

    const userDataWithCallback = React.useCallback((l, i) => {
       return (
          <> // maybe a key prop is needed too
             <Input
                label='First Name'
                value={l.name}
                onChangeText={setname} /> 
    
             <Button
                title="Modify"
                onPress={() => modifyDetails(name)} />
          </>
      )
    }, [])
    
    userdata.map((l, i) => (
       userDataWithCallback(l, i)
    ))