Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native detect tap on View

Tags:

react-native

I’m writing a React Native app and I want to detect tap/clicks anywhere on the screen so I put an onClick handler on my <View> element but it doesn’t seem to be working. Here is my render function:

<View style={styles.container} onClick={this.onClick}>
    <Text style={styles.welcome}>
        Tap to change the background
    </Text>
</View>

What do I need to do?

like image 870
Hum4n01d Avatar asked Jan 31 '17 02:01

Hum4n01d


3 Answers

For making any element to handle touch/click events in a React-Native UI, you need to put the element inside a TouchableOpacity, TouchableWithoutFeedback, TouchableNativeFeedback or TouchableHighlight element:

<TouchableHighlight onPress = { this.onClick }>
    <View style={styles.container}>
    <Text style={styles.welcome}>
        Tap to change the background
    </Text>
    </View>
</TouchableHighlight>

Hope that helps.

like image 101
adonike Avatar answered Nov 20 '22 15:11

adonike


In React Native version > 55.3 you make check onPress events into your View if use onStartShouldSetResponder props.

Like example:

<View 
    style={{ flex: 1 }}
    onStartShouldSetResponder={() => console.log('You click by View')}
 >

    <ScrollView 
        refreshControl={
           <RefreshControl 
               refreshing={this.state.refreshing}
               onRefresh={this.onRefresh} />
           }
      >

     <Text>Awesome</Text>

    </ScrollView>
</View>

In example I showed how you can get onPress event on View and not blocking other event behind them. Refresh control still work correct.

like image 27
Andrey Patseiko Avatar answered Nov 20 '22 13:11

Andrey Patseiko


In my case the following works fine. You can use onTouchStart and onTouchEnd handlers on any View via props, for example:

<View onTouchStart={() => this.doSomething()} />

More information

like image 12
Roman Avatar answered Nov 20 '22 13:11

Roman