Search code examples
androidreact-nativeandroid-buttonandroid-theme

How do I change the theme when I press the button? (React-native)


When I press the button, I want it to get button2 theme instead of buttondefault. How can I do it? (I couldn't find it in the react-native documents, is there a link?)

export default class deneme extends Component {
  constructor(props) {
    super(props);
    this.state = {
           

    
    };
  }


  render() {
    return (
      <View style={{flex:1, justifyContent:'center', alignItems:'center'}}>

        <TouchableOpacity 
        onPress={() => this.pressme()}
        style={styles.buttondefault}>
        <Text style={{fontSize:40}}> B </Text>
        </TouchableOpacity>

      </View>
    );
  }
}

const styles = StyleSheet.create({
    buttondefault:{
        width:100,
        height:50,
        backgroundColor:'green'
    },

    button2:{
        width:50,
        height:100,
        backgroundColor:'green'
    },


});

Solution

  • You can have a state for this button, and clicking the button will change the state which in turn will change the style like so:

    constructor(props) {
      super(props);
      this.state = {
        buttonStyle: 'default' 
      };
    }
    ...
    ...
    <TouchableOpacity 
      onPress={() => this.pressme()}
      style={(this.state.buttonStyle == 'default') ? styles.buttondefault : styles.button2}>
      <Text style={{fontSize:40}}> B </Text>
    </TouchableOpacity>
    ...
    ...
    pressme() {
      this.setState({buttonStyle: 'button2'});
    }