0
0
React Nativemobile~3 mins

Why TouchableOpacity and TouchableHighlight in React Native? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to make your app's buttons feel alive with just a simple wrapper!

The Scenario

Imagine you want to make a button in your app that changes color or looks different when you press it, just like a real button does in everyday life.

You try to do this by manually changing styles every time the user touches the button.

The Problem

Doing this by hand means writing lots of code to track when the button is pressed and released.

This can get messy, slow, and easy to make mistakes.

You might forget to reset the style or make the button flicker in a weird way.

The Solution

TouchableOpacity and TouchableHighlight are ready-made tools that handle all the touch feedback for you.

They automatically change the button's look when pressed, making your app feel smooth and natural without extra work.

Before vs After
Before
const [pressed, setPressed] = useState(false);
<View
  onTouchStart={() => setPressed(true)}
  onTouchEnd={() => setPressed(false)}
  style={{backgroundColor: pressed ? 'gray' : 'blue'}}>
  <Text>Press me</Text>
</View>
After
<TouchableOpacity onPress={() => Alert.alert('Pressed!')}>
  <Text>Press me</Text>
</TouchableOpacity>
What It Enables

It lets you create buttons and touchable elements that feel responsive and polished with almost no extra code.

Real Life Example

Think about a shopping app where you tap "Add to Cart" and the button dims slightly to show your tap was registered instantly.

Key Takeaways

Manually handling touch feedback is complicated and error-prone.

TouchableOpacity and TouchableHighlight simplify this by managing touch states automatically.

Using them makes your app feel smooth and professional with less code.