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.

3 thoughts on “How to Set onPress Function to an Image in React Native”

  1. Hi, cool, but what happens if you press on the white area not covered by the image? Will that area also be affected by the TouchableOpacity? Im thinking, if you have an image that is smaller than the 500*500 then there will be space around it. If you only want to have the touchable on the image if image is ex. 100*100 or change in size. Just a question. 🙂

Leave a Reply

%d bloggers like this: