How to change button color when pressed in React Native using TouchableHighlight?

5.1k views Asked by At

I am currently developing an application, and I am having trouble figuring out how to get the button to change color after being pressed using TouchableHighlight. Not to be confused with the underlayColor prop which I know exists as part of TouchableHighlight which only changes the color for when the button is pressed and then returns to its regular color.

This is what I have so far (Some of the code has been omitted for simplicity):

import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TouchableHighlight,
Alert,
} from 'react-native';


class MeetingScreen extends Component {
  constructor(props){
       super(props);
       this.state = {
        buttonColor: '#7395AE',
        }
this.onButtonPress=this.onButtonPress.bind(this);

  }

onButtonPress(){
  this.setState({ buttonColor: 'red' });
}

    render() {
  return (
    <View style={styles.container}>
      <TouchableHighlight
        style={styles.talk}
        color={this.state.buttonColor}
        onPress={() => this.state.buttonColor}
        selected={this.onButtonPress}
      >
        <View>
          <Text style={styles.welcome} >
            Talk
          </Text>
        </View>
      </TouchableHighlight>
    </View>
  );
}
};


const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#7395AE',
  },
  welcome: {
    fontSize: 30,
    textAlign: 'center',
    margin: 10,
    color: '#ffffff',
  },
  talk:{
    height: 200,
    width: 200,
    borderWidth: 5,
    backgroundColor: '#7395AE',
    borderRadius: 100,
    borderColor: '#557A95',
    justifyContent:'center',
    alignItems:'center',
    borderRadius: 100
  },
});

export default connect(mapStoreToProps, mapDispatchToProps)(MeetingScreen);

I have looked at other answers on StackOverflow and have attempted a good portion of them but I couldn't find anything that fit specifically to my issue. I have also looked at the React Native documentation and wasn't able to find anything helpful. The code as it is right now just displays the button and when pressed it goes black but then goes back to it's original color after being pressed. What I am looking for is for the button to turn red and stay red after being pressed. Any help would be greatly appreciated. Thank you so much for any help in advance!

1

There are 1 answers

1
jose920405 On
<TouchableHighlight
  style={[styles.talk, { backgroundColor: this.state.buttonColor}]} //Or if don't want "backgroundColor:" and just need change the text color use => "color:""
  onPress={() => this.state.buttonColor}
  selected={this.onButtonPress}/>