Shashika Virajh
Shashika Virajh

Reputation: 9487

Touchable Opacity onPressIn color change

I have the following code in my React-Native application.

     <TouchableOpacity
       // onPress={onPress}
       onPressIn={this.handlePressIn}
       onPressOut={this.handlePressOut}
       disabled={disabled}
       style={[
         styles.button,
         buttonStyle,
         this.buttonStyles(),
       ]}
       >
         <Text>Hello</Text>
       </TouchableOpacity> 

I want to change the color of TouchableOpacity when it is being pressed. So, in onPressIn, I changed the color to darkRed, but it display a light red or something similar to that. No dark color can be set there. What is the issue here? How can I change the color till I onPressOut? The color should be a dark one.

Upvotes: 4

Views: 8142

Answers (2)

Shashika Virajh
Shashika Virajh

Reputation: 9487

Found the solution. Set your activeOpacity={1} in your TouchableOpacity.

<TouchableOpacity
    onPress={onPress}
    activeOpacity={1}
/>

Upvotes: 6

Tim
Tim

Reputation: 10719

Edit:

I guess I overengineered it a little bit. You can simply use the activeOpacity={1} prop.

Problem:

The problem is that TouchableOpacity already provides feedback by reducing the opacity of the button, allowing the background to be seen through while the user is pressing down. So even if you change the backgroundcolor of the button, you won't notice it. Fortunately, I have a solution for you.

Solution:

You can use TouchableWithoutFeedback together with an additional View to create your wanted behavior.

Code:

<TouchableWithoutFeedback
onPressIn={() => this.setState({pressIn: true })}
onPressOut={() => this.setState({pressIn: false})}
>
<View
// change the color depending on state 
style={{ backgroundColor: this.state.pressIn ? '#4c7d4c': '#98FB98'}} 
>
   <Text> Custom Button </Text>
</View>
</TouchableWithoutFeedback>

Output:

demo

Working Example:

https://snack.expo.io/@tim1717/quiet-watermelon

Upvotes: 5

Related Questions