Home > Software design >  Why are this Inputs sharing the same value?
Why are this Inputs sharing the same value?

Time:01-18

I have this Input component

const Input = (props) => {
    return (
        <View>
            <TextInput
                onChangeText={(text) => {
                    props.setValue(text);
                }}
            />
        </View>
    )
}

I use it in this code, there are two different views that can be rendered, but the value of one input gets shared with the other, when i write something in one and change to the other view, the same thing i wrote appears in this input.

const [emailScreen, setEmailScreen] = useState(false);

const [name, setName] = useState('');
const [lastNames, setLastNames] = useState('');
const [email, setEmail] = useState('');
{ !emailScreen ? (
                // But for example in this view where there are two inputs, tha value
                // doesn't get shared between them.

                <View style={styles.inputsContainer}>
                    // It only shares the same thing this one
                    <Input
                        setValue={(value) => {
                            setName(value);
                        }}
                    />
                    <Input
                        setValue={(value) => {
                            setLastNames(value);
                        }}
                    />
                </View>
            ) : (
                <View>
                    // With this one
                    <Input                        
                        setValue={(value) => {
                            setEmail(value);
                        }}
                    />
                </View>
)}

Here is the full code :

https://codeshare.io/3ApDzv

https://codeshare.io/j0ve7P

CodePudding user response:

As @windowsill said, your inputs are not controlled.

Please add the value prop to your text inputs.

For your Input:

const Input = (props) => {
    return (
        <View>
            <TextInput
                onChangeText={(text) => {
                    props.setValue(text);
                }}
                value={props.value} // <- add value prop here
            />
        </View>
    )
}

For the instances of your Input components:

{ !emailScreen ? (
  <View style={styles.inputsContainer}>
      // It only shares the same thing this one
      <Input
          value={name} // <- add here
          setValue={(value) => {
              setName(value);
          }}
      />
      <Input
          value={lastName} // <- add here
          setValue={(value) => {
              setLastNames(value);
          }}
      />
  </View>
) : (
  <View>
      // With this one
      <Input                        
          setValue={(value) => {
              setEmail(value);
          }}
          value={email} // <- add here
      />
  </View>
)}
  •  Tags:  
  • Related