'Change button style on press in React Native

I'd like the style of a button in my app to change when it is being pressed. What is the best way to do this?



Solution 1:[1]

Use the prop:

underlayColor

<TouchableHighlight style={styles.btn} underlayColor={'gray'} />

https://reactnative.dev/docs/touchablehighlight

Solution 2:[2]

React Native now provides a new Pressable component that can detect various stages of press interactions. So, in order to change the color(in general any style) of the component, refer below example:

<Pressable
  style={({ pressed }) => [{ backgroundColor: pressed ? 'black' : 'white' }, styles.btn ]}>
  {({ pressed }) => (
    <Text style={[{ color: pressed ? 'white' : 'black' }, styles.btnText]}>
      {text}
    </Text>
  )}
</Pressable>

Code breakdown:

style={({ pressed }) => [{ backgroundColor: pressed ? 'black' : 'white' }, styles.btn ]}

Here the style prop receives pressed(boolean) that reflects whether Pressable is pressed or not and returns an array of styles.

{({ pressed }) => (
    <Text style={[{ color: pressed ? 'white' : 'black' }, styles.btnText]}>
      {text}
    </Text>
)}

Here the text style too can be modified as the pressed is also accessible to the children of Pressable component.

Solution 3:[3]

This is Besart Hoxhaj's answer in ES6. When i answer this, React Native is 0.34.

 import React from "react";
 import { TouchableHighlight, Text, Alert, StyleSheet } from "react-native";

 export default class TouchableButton extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        pressed: false
    };
}
render() {
    return (
        <TouchableHighlight
            onPress={() => {
                // Alert.alert(
                //     `You clicked this button`,
                //     'Hello World?',
                //     [
                //         {text: 'Ask me later', onPress: () => console.log('Ask me later pressed')},
                //         {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
                //         {text: 'OK', onPress: () => console.log('OK Pressed')},
                //     ]
                // )
            }}
            style={[
                styles.button,
                this.state.pressed ? { backgroundColor: "green" } : {}
            ]}
            onHideUnderlay={() => {
                this.setState({ pressed: false });
            }}
            onShowUnderlay={() => {
                this.setState({ pressed: true });
            }}
        >
            <Text>Button</Text>
        </TouchableHighlight>
    );
}
}

const styles = StyleSheet.create({
button: {
    padding: 10,
    borderColor: "blue",
    borderWidth: 1,
    borderRadius: 5
}
});

Solution 4:[4]

use something like that :

class A extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      onClicked: false
    }
    this.handlerButtonOnClick = this.handlerButtonOnClick.bind(this);
  }
  handlerButtonOnClick(){
    this.setState({
       onClicked: true
    });
  }
  render() {
    var _style;
    if (this.state.onClicked){ // clicked button style
      _style = {
          color: "red"
        }
    }
    else{ // default button style
      _style = {
          color: "blue"
        }
    }
    return (
        <div>
            <button
                onClick={this.handlerButtonOnClick}
                style={_style}>Press me !</button>
        </div>
    );
  }
}

If you use an external CSS, you can use className in place of style property :

render() {
    var _class = "button";
    var _class.concat(this.state.onClicked ? "-pressed" : "-normal") ;
    return (
        <div>
            <button
                onClick={this.handlerButtonOnClick}
                className={_class}>Press me !</button>
        </div>
    );
  }

It doesn't really matter how do you apply your CSS. Keep your eyes on the "handlerButtonOnClick" method.

When the state change, the component is re-rendered ("render" method is called again).

Good luck ;)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FrostyDog
Solution 2 Ankush Chauhan
Solution 3 Mojtaba Moshfeghi far
Solution 4 sami ghazouane