Hoang Tuan Nguyen
Hoang Tuan Nguyen

Reputation: 21

Change a text color by using onPress on React Native

I have 3 TouchableHighLight in my view. It's all have text color is white. I want when I press one of buttons, text color will change green. But when I press it, all text color in button will change color green. Please help me.

Upvotes: 1

Views: 9427

Answers (4)

Carlos Jose
Carlos Jose

Reputation: 65

In this case I would recommend using the Pressable API and its children prop.

      <Pressable
        children={({ pressed }) => (
          <Text style={{ color: pressed ? '#FF9E00' : '#222'}}>
            text
          </Text>
        )}/>

This way when clicking on one item, only that item changes color.

Upvotes: 5

Hoang Tuan Nguyen
Hoang Tuan Nguyen

Reputation: 21

this is my code: this.state = { textColor: 'white' }

_onPressIn = () => {
    this.setState({
        textColor: 'green'
    });
}

_onPressOut = () => {
    this.setState({
        textColor: 'white'
    });
}

LOGIN

I have three button like this, I want when I click one of button just change text color, another text button don't change

Upvotes: 0

Sel&#231;uk İtmiş
Sel&#231;uk İtmiş

Reputation: 9

You have to use style attribute to change color of text. Like this

style={{color : this.state.colorCode}}

Also you can use default value without state

style={{color : this.state.colorCode || "YOUR DEFAULT COLOR"}}

Upvotes: 0

Muhammad Danish Kiani
Muhammad Danish Kiani

Reputation: 93

Kindly try this, You can initialise the default color to be white in constructor, follow this for you other buttons,hope this will help.

<TouchableHighLight style = {{height: 20, width:20}} onPress = {()=> this.setState(colorCode: 'green')}>
<Text>{this.state.colorCode}</Text>
</TouchableHighLight>

Upvotes: 0

Related Questions