How to Set OnPress Function to View in React Native

Last Updated on December 13, 2020.

In react native, we use onPress prop in touchable components to enable pressing functionality. But, what about having onPress function for the View component itself? This feature is one of the things I was missing when I compare react native to native Android development.

If you are using react native version greater than 0.55.3 then you can add onPress kind of functionality to any View component using onStartShouldSetResponder prop. This prop makes the view responds on the start of touch- which is strikingly similar to the onPress prop of other components.

In the following react native view on press example, I have a view component with onStartShouldSetResponder prop which invokes an Alert function. This means the alert will appear when the view is pressed. That’s how you add onPress functionality to View in React Native.


import React from 'react';
import {View, Alert, StyleSheet} from 'react-native';

const Home = () => {
  return (
    <View style={styles.container}>
      <View
        style={styles.view}
        onStartShouldSetResponder={() =>
          Alert.alert('OnPress', 'Clicked on View')
        }
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'white',
  },
  view: {
    height: 100,
    width: '100%',
    backgroundColor: '#00BCD4',
  },
});

export default Home;

The output will be as given below.

Leave a Reply

%d bloggers like this: