How to Set OnPress Function to View in React Native

In react native, we use onPress prop in touchable components to enable pressing functionality. But, what about having an 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 the onStartShouldSetResponder prop. This prop makes the view responds at 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 App = () => {
  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 App;

The output will be as given below.

react native view onpress

I hope this tutorial of react native View onPress is useful for you.

Similar Posts

Leave a Reply