I am trying to have more than one switch on the same page, I succeeded but the problem is that when I click on a switch it modifies all the other switches.
Here is my code
const Setting =() => {
const [switchValue, setSwitchValue] = useState(false);
const toggleSwitch = (value, nb) => {
setSwitchValue(value);
};
return (
<View>
<View style={styles.Container}>
<Text style={styles.Title}>Change Profil Setting</Text>
</View>
<View style={styles.ContainerText}>
<Text syle={styles.Normal}>Over 18:</Text>
<Switch
style={{left: 50}}
onValueChange={toggleSwitch}
value={switchValue}
/>
</View>
<View style={styles.ContainerText}>
<Text syle={styles.Normal}>AutoPlay:</Text>
<Switch
style={{left: 50}}
onValueChange={toggleSwitch}
value={switchValue}
/>
</View>
<View style={styles.ContainerText}>
<Text syle={styles.Normal}>FlexDirecttion:</Text>
<Switch
style={{left: 50}}
onValueChange={toggleSwitch}
value={switchValue}
/>
</View>
</View>
)
}
CodePudding user response:
const Setting =() => {
const [switchValue, setSwitchValue] = useState(false);
const [switch2Value, setSwitch2Value] = useState(false);
const [switch3Value, setSwitch3Value] = useState(false);
const toggleSwitch = (value, nb) => {
setSwitchValue(value);
};
const toggle2Switch = (value, nb) => {
setSwitch2Value(value);
};
const toggle3Switch = (value, nb) => {
setSwitch3Value(value);
};
return (
<View>
<View style={styles.Container}>
<Text style={styles.Title}>Change Profil Setting</Text>
</View>
<View style={styles.ContainerText}>
<Text syle={styles.Normal}>Over 18:</Text>
<Switch
style={{left: 50}}
onValueChange={toggleSwitch}
value={switchValue}
/>
</View>
<View style={styles.ContainerText}>
<Text syle={styles.Normal}>AutoPlay:</Text>
<Switch
style={{left: 50}}
onValueChange={toggle2Switch}
value={switch2Value}
/>
</View>
<View style={styles.ContainerText}>
<Text syle={styles.Normal}>FlexDirecttion:</Text>
<Switch
style={{left: 50}}
onValueChange={toggle3Switch}
value={switch3Value}
/>
</View>
</View>
)
}
This can be considered as a work around. What I would suggest is wrap the Switch component inside another component and import it where-ever you want by incorporating the state management in that component.