Home > Enterprise >  How to change button color of app using switch with React native
How to change button color of app using switch with React native

Time:09-29

I want my red button to change color when the switch button is active. How can I do it? In this way, I want to change the colors on other pages with the switch.

App Image

export function SettingsAccountScreen(props) {
const { navigate } = props.navigation;
const [isEnabled, setIsEnabled] = React.useState(false);
  const toggleSwitch = () => setIsEnabled(previousState => !previousState);
return(
  <SafeAreaView>
  <View style = {styles.container}>
            <TouchableOpacity onPress ={() => {navigationService.navigate('MyAccount', null);} 
          }>
              <Image style= {styles.imageSt} source={require('../../assets/arrow-left-circle.png')} />
            </TouchableOpacity>
            <View style = {styles.textView}>
              <Text style = {styles.textStyle}>Uygulama Ayarları</Text>
            </View>
</View>
<View style={styles.container}>
      <Switch
        trackColor={{ false: "#767577", true: "#81b0ff" }}
        thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
        ios_backgroundColor="#3e3e3e"
        onValueChange={toggleSwitch}
        value={isEnabled}
      />
    </View>
<View>
  <TouchableOpacity style={{backgroundColor: "red", marginTop: 50}}>
    <Text>
      Deneme Buton
    </Text>
  </TouchableOpacity>
</View>
</SafeAreaView>
)}

CodePudding user response:

You just need to update styles depending on Switch state.

....Other Code....
<TouchableOpacity style={{backgroundColor: isEnabled ? "green":"red", marginTop: 50}}>
<Text>
  Deneme Buton
</Text>

CodePudding user response:

You can change the button color on the basis of your condition.

<TouchableOpacity style={{backgroundColor: isEnabled ? "Color1":"Color2", marginTop: 50}}>
<Text>
  Deneme Buton
</Text>

For storing the value you have many options

  • Asyncstorage
  • By passing the parameter
  • useContext

By passing paramter: navigate(RoutName, {your value}) from screen 1 and get it to second Screen and send it to back.

  • Related