How to Set onPress Function to an Image in React Native

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

If you want to add an onPress prop to the image, then you have to use the Pressable 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, Pressable, Image, View, Alert} from 'react-native';

const Home = () => {
  return (
    <View>
      <Pressable 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}
        />
      </Pressable>
    </View>
  );
};

export default Home;

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

Following is the output of this tutorial.

react native clickable image

That’s how you add a clickable image in react native easily.

Similar Posts

3 Comments

  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