0

I'm using react-native. I need to show a menu that consists of a list of items. I simplified the code below and I'm showing only a text but in the real case, the item has got a checkbox an icon and a label so for this reason I created a custom component. I need to handle the on click on the items. The problem is that the on press on the TouchableOpacity in the widget is not triggered. If I use the same hierarchy of components directly the on click works.

So in the example below the onClick on the TouchableOpacity that is directly put in the containing view is triggered but the onClick on the TouchableOpacity that is wrapped in the EventOnMapMenuWidget is not triggered.

How can I handle the onClick on the TouchableOpacity in the EventOnMapMenuWidget?

Please notice that in the log I don't see the

EventOnMapMenuWidget onPress

while I see the

TEST onPress

private drawEventsOnMapForm() {
    return <View style={{ margin: marginStyle.medium, flexDirection: 'column' }}>
            <EventOnMapMenuWidget
                onToggle={() => {
                    console.log("EventOnMapMenuWidget onToggle")
                }}
                label={STRINGS.speeding}
            />
            <TouchableOpacity style={{ margin: marginStyle.medium, flexDirection: 'row' }} onPress={() => {
                console.log("TEST onPress")
            }}>
                <Text style={{ color: COLORS.black }}>{STRINGS.speeding}</Text>
            </TouchableOpacity>
        </View>
}

This is the definition of the custom components:

export default class EventOnMapMenuWidget extends Component<EventOnMapMenuWidgetProp> {
    render() {
        return <TouchableOpacity style={{ margin: marginStyle.medium, flexDirection: 'row' }} onPress={()=> {
            console.log("EventOnMapMenuWidget onPress", this.props.label)
            this.props.onToggle()
        }}>
            <Text style={{color: COLORS.black}}>{this.props.label}</Text>
        </TouchableOpacity>
    }
}
kingston
  • 11,053
  • 14
  • 62
  • 116
  • This seems to work as expected. https://snack.expo.io/@nipuna777/fascinated-milkshake You could try adding backgroundColors to TouchableOpacity to make sure that they are positioned where they should be. – nipuna-g Feb 22 '21 at 01:10
  • Thank you @nipuna777. For some reasons in the app, it does not work. I have even tried to create another snipped like yours where I copied almost everything I have in the app. It is still working but it doesn't in the app. I managed to make it work using a View instead of the TouchableOpacity and wrapping the View with a Button. It is not ideal but it works. – kingston Feb 22 '21 at 21:13
  • this was the answer: https://stackoverflow.com/a/56090392/987753 – kingston Mar 13 '21 at 16:28

0 Answers0