How to enable both parent and child press event in react native?

Viewed 678
<TouchableOpacity onPress={()=> onParentClick()}>
  <SomeImportedComponentWithTouchableOpacityInsideIt />
</TouchableOpacity>

Both "TochableOpacity"s imported from "react-native"

Issue: onParentClick() is not being triggered but the inner onPress works as expected.

1 Answers

Output:

enter image description here

Make the Child smaller than the Parent so that you will have the clickable body of the parent too.

Here is an example:

import React, { useState } from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';

// You can import from local files
import AssetExample from './components/AssetExample';

// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';

export default function App() {
  const [text, setText] = useState('Nothing Clicked');
  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>{text}</Text>
      <TouchableOpacity
        style={styles.parent}
        onPress={() => {
          setText('Pressed From Parent');
        }}>
        <ChildComponent onCLick={setText}/>
        </TouchableOpacity>
    </View>
  );
}

const ChildComponent = ({ onCLick }) => {
  return (
    <TouchableOpacity
      style={styles.child}
      onPress={() => {
        onCLick('Pressed From Child');
      }}>
      
      </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
    alignItems: 'center',
  },

  parent: {
    padding: 20,
    backgroundColor: 'teal',
    borderRadius: 5,
  },
  child: {
    
    width: 200,
    height: 100,
    backgroundColor: 'orange',
    borderRadius: 5,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

You can play with the working example here: Expo Snack Link

Related