0

In TouchableOpacity, it is possible to set the value of the activeOpacity prop to dim the button after it was pressed, so the user had feedback that their touch was registered and does not pressing the same button repeatedly.

Is there anything similar in the new Pressable component? Or any way to easily achieve the same effect?

ahron
  • 803
  • 6
  • 29

1 Answers1

2

You can try the following example to achieve the same functionality:

import React, { useState } from 'react';
import { Pressable, StyleSheet, Text, View } from 'react-native';

const App = () => {
  const [timesPressed, setTimesPressed] = useState(0);

  let textLog = '';
  if (timesPressed > 1) {
    textLog = timesPressed + 'x onPress';
  } else if (timesPressed > 0) {
    textLog = 'onPress';
  }

  return (
    <View style={styles.container}>
      <Pressable
        onPress={() => {
          setTimesPressed((current) => current + 1);
        }}
        style={({ pressed }) => [
          {
            backgroundColor: 'gray',
            opacity: pressed ? 0.2 : 1,
          },
          styles.wrapperCustom
        ]}>
        {({ pressed }) => (
          <Text style={styles.text}>
            {pressed ? 'Pressed!' : 'Press Me'}
          </Text>
        )}
      </Pressable>
      <View style={styles.logBox}>
        <Text testID="pressable_press_console">{textLog}</Text>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
  },
  text: {
    fontSize: 16
  },
  wrapperCustom: {
    borderRadius: 8,
    padding: 6
  },
  logBox: {
    padding: 20,
    margin: 10,
    borderWidth: StyleSheet.hairlineWidth,
    borderColor: '#f0f0f0',
    backgroundColor: '#f9f9f9'
  }
});

export default App;

TL;DR;

<Pressable
  style={({ pressed }) => [
    { opacity: pressed ? 0.2 : 1}, styles.wrapperCustom,
  ]}>
  {({ pressed }) => (
    <Text style={styles.text}> {pressed ? 'Pressed!' : 'Press Me'} </Text>
  )}
</Pressable>
Olcay Ertaş
  • 5,987
  • 8
  • 76
  • 112
Dipan Sharma
  • 1,114
  • 7
  • 17
  • 1
    Nice answer, thanks. So you are using the `Pressed` boolean value to conditionally modify the opacity and text. For future readers, it will be better if your answer also explained the approach a little bit. – ahron May 15 '21 at 10:33