CodeBlanks Logo Icon CodeBlanks

TouchableOpacity

Learn touch with TouchableOpacity.

What is TouchableOpacity?

TouchableOpacity is a wrapper component that makes its content clickable. When pressed, it becomes slightly transparent; this provides visual feedback.

Its most used prop is onPress. It takes a function; called when pressed. Example: <TouchableOpacity onPress={increment}><Text>Increase</Text></TouchableOpacity>.

You must import TouchableOpacity from react-native.

Wiring the buttons

We will wire the increment and decrement functions to TouchableOpacity buttons. This way when the user presses a button, the function runs.

We will add two buttons: <TouchableOpacity onPress={increment}><Text>Increase</Text></TouchableOpacity> and <TouchableOpacity onPress={decrement}><Text>Decrease</Text></TouchableOpacity>.

We will place them inside a <View>, below the counter text.

Practice Add the buttons

Add two <TouchableOpacity> buttons to the existing App. The first has onPress={increment} and contains <Text>Increase</Text>; the second has onPress={decrement} and contains <Text>Decrease</Text>. Do not forget to import TouchableOpacity.

Starter code

App.js
import { View, Text } from 'react-native';
import { useState } from 'react';

export default function App() {
  const [count, setCount] = useState(0);

  function increment() {
    setCount(count + 1);
  }

  function decrement() {
    setCount(count - 1);
  }

  return (
    <View>
      <Text>Counter: {count}</Text>
    </View>
  );
}

Sample solution

App.js
import { View, Text, TouchableOpacity } from 'react-native';
import { useState } from 'react';

export default function App() {
  const [count, setCount] = useState(0);

  function increment() {
    setCount(count + 1);
  }

  function decrement() {
    setCount(count - 1);
  }

  return (
    <View>
      <Text>Counter: {count}</Text>
      <TouchableOpacity onPress={increment}>
        <Text>Increase</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={decrement}>
        <Text>Decrease</Text>
      </TouchableOpacity>
    </View>
  );
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which prop does TouchableOpacity use for clicks?

  • onPress Correct answer
  • press
  • onTouch
  • onClick

Explanation: onPress catches the click event.

2 TouchableOpacity opening

Question
<____ onPress={increment}><Text>Increase</Text></TouchableOpacity>
Answer
<TouchableOpacity onPress={increment}><Text>Increase</Text></TouchableOpacity>

Explanation: TouchableOpacity is the clickable wrapper.

3 Match the button parts

Term Meaning
TouchableOpacity Clickable wrapper
onPress Click event
increment Increment function
<Text> Button label

All lessons in Beginner