I am trying to change the Background Color of the entire View by a toggle switch. But the color is not changing. Please help and Big Thanks!
Here is my code.
import { StyleSheet, View, Switch} from 'react-native';
import React, {useState} from 'react';
export default function App() {
const [isEnabled, setIsEnabled] = useState(false);
const toggleSwitch = () => setIsEnabled(previousState => !previousState);
const [color, setColor] = React.useState('yellow');
return (
<View style={[styles.container,
{backgroundColor:color}]}
onValueChange = {color => setColor(color)}>
<Switch onValueChange={toggleSwitch}
value={isEnabled} onClick={() => setColor('grey')}>
</Switch>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection:'column',
alignItems:'center',
justifyContent: 'center'
}
});
3
Answers
You need to add conditional styling on the view where you want the color to be changed. Keep it simple and not confuse it. It would be something like this.
You need to define what happens when switch is enabled and what happens when switch is disabled. If enabled (conditional styling) background will be yellow, if not it’ll be grey.
If you just want to change the Bg-color to grey.
If you want to change the Bg-color to "grey" when Switch is disabled and "yellow" when the Switch is enabled