How to Set onPress Function to an Image in React Native

Last Updated on December 11, 2020.

As you know, the Image component of React Native doesn’t have an onPress prop. Hence, you can’t directly set the onPress function to an image in React Native.

If you want to add onPress prop to the image, then you have to use the TouchableOpacity component of React Native. Touchable Opacity has onPress prop and you can embed the Image component inside it.

In the following example, we show an alert when the image is pressed.

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

const Home = () => {
  return (
    <View>
      <TouchableOpacity onPress={() => Alert.alert('image clicked')}>
        <Image
          source={{
            uri:
              'https://cdn.pixabay.com/photo/2020/05/04/23/06/spring-5131048_960_720.jpg',
          }}
          style={styles.image}
        />
      </TouchableOpacity>
    </View>
  );
};

export default Home;

const styles = StyleSheet.create({
  image: {
    height: 500,
    width: 500,
  },
});

Following is the output of this tutorial.

react native image press

That’s how you add onpress function to image in react native.

1 thought on “How to Set onPress Function to an Image in React Native”

Leave a Reply

%d bloggers like this: