Mohammad Haque
Mohammad Haque

Reputation: 565

TouchableOpacity with multiple child with onPress

I have FlatList with custom row item wrappen inside a TouchableOpacity. I would like to have multiple onPress inside the TouchableOpacity so that each child view can handle their respected job. Problem is that while on pressing the child view it does it's job but also parent onPress also gets executed. How to stop that?

<TouchableOpacity onPress={ () => this.doSomething()}>
  <Text>Some content</Text>
  <Icon name="trash" size={20} onPress={this.onDeleteItem(item)}/>
<TouchableOpacity>

In another word how to execute only onDeleteItem when user press on trash icon?

Any suggestion appreciated, thanks.

Upvotes: 5

Views: 5050

Answers (3)

Add inside child function

e.preventDefault()

in suc an example

<TouchableOpacity onPress={() => this.doSomething()}>
  <Text>Some content</Text>
  <Icon name="trash" size={20} onPress={(e) => {
    e.preventDefault()
    this.onDeleteItem(item)
  }}/>
<TouchableOpacity>

Upvotes: 1

Sjonchhe
Sjonchhe

Reputation: 828

You will have to use Containers from native-base in order to use zIndex properly. I also suffered allot because of zIndex. Then with containers it was working fine.

Upvotes: 1

Gavin Thomas
Gavin Thomas

Reputation: 1867

Move your first onPress to the Text, or where-ever is more appropriate than the outer most container.

<TouchableOpacity>
  <Text onPress={ () => this.doSomething()} >Some content</Text>
  <Icon name="trash" size={20} onPress={this.onDeleteItem(item)}/>
<TouchableOpacity>

Theres no way to avoid an event listener on the parent TouchableOpacity because it's wrapping all content. You would need to add some Containers/Contents (NativeBase) to modularize it more.

Upvotes: 0

Related Questions