Pratik Bhattacharya
Pratik Bhattacharya

Reputation: 3746

Getting events from a disabled TouchableOpacticity in React Native

I want to collect some data about how many users are pressing a disabled button (implemented using TouchableOpacity) in my React-Native app? Since I am passing disabled=true to the element, the onPress event handler is not getting executed?

Is there any way to listen to events from a disabled TouchableOpacity.

My last resort is to simply make the button look disabled, and capture the onPress event, but I am looking for some tricks to capture event from the disabled element directly.

Upvotes: 0

Views: 355

Answers (1)

PhantomSpooks
PhantomSpooks

Reputation: 3540

According to the docs, TouchableOpacity inherits all the props from TouchableWithoutFeedback, and the disabled prop there disables all interactions, so the onPress event is never fired. As you guessed, the best course of action is to make the button appear disable:

import React, { useState } from 'react';
import {
  Text,
  View,
  StyleSheet,
  TouchableOpacity,
} from 'react-native';
import LabeledSwitch from './components/LabeledSwitch';
export default function App() {
  const [buttonIsActive, setButtonIsActive] = useState(false);
  
  const onButtonPressed = ({ nativeEvent }) => {
    if (!buttonIsActive) {
      // do your data gathering
      console.log(nativeEvent);
      return;
    }
    // do default button stuff
  };
  return (
    <View style={styles.container}>
      <LabeledSwitch
        label="Set button active"
        currentValueMessage={
          'Button is ' + (buttonIsActive ? 'active' : 'inactive')
        }
        value={buttonIsActive}
        onValueChange={setButtonIsActive}
      />
      <TouchableOpacity
        style={[styles.touchable, !buttonIsActive && styles.disabledButton]}
        onPress={onButtonPressed}
        // since we are faking disabling the button we will need to
        // hide touch animations when the button is disabled
        activeOpacity={buttonIsActive ? 0.2 :styles.disabledButton.opacity}
        >
        <Text style={[styles.text,!buttonIsActive && styles.disabledButton]}>Press me</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  touchable: {
    borderRadius: 10,
    backgroundColor: 'lightgreen',
    borderColor: 'green',
    borderWidth: 1,
    alignItems: 'center',
    padding: 5,
    margin: 2,
    width: '50%',
    alignSelf: 'center',
  },
  disabledButton: {
    opacity: 0.8,
  },
  text:{
    color:'darkgreen',
    fontSize:18
  }
});

Here's the snack

Upvotes: 1

Related Questions