Set onPress onClick to Image in React Native using TouchableOpacity

How to add click listener on Image View and on onPress() method call function from same class and show alert message on application screen.

Image buttons is very popular between developers because using them Android and iOS both developers can create simple cool looking buttons. So in this tutorial we would going to set onPress  method on Image using TouchableOpacity. Because by default Image dose not support proper onPress method. So let’s get started 😉 .

Contents in this project Set onPress onClick to Image :-

  1. Start a fresh React Native project. If you don’t know how then read my this tutorial.
  2. Add Image, StyleSheet, View and TouchableOpacity component in import block.
  3. Create folder for image inside your project’s folder and put your image in it.
  4. Add View tag in render’s return block.
  5. Add TouchableOpacity in render’s return block inside View tag.
  6. Add Image tag inside TouchableOpacity block.
  7. Create function inside your Main class named as callFun .
  8. Add activeOpacity and onPress on TouchableOpacity.
  9. Calling callFun function on onPress  on TouchableOpacity.
  10. Add Source attribute in Image tag and Assign image path using require.
  11. Create StyleSheet just above the AppRegistry.registerComponent line.
  12. Inside StyleSheet create two styles Container for complete View and BorderClass for Image.
  13. Call css class into both View and Image tag.
  14. Complete Source Code.

1. Start a fresh React Native project. If you don’t know how then read my this tutorial.

2. Add ImageStyleSheet, View and TouchableOpacity component in import block.

3. Create folder for image inside your project’s folder and put your image in it.

  1. Open your project folder for example my project name is Myproject -> Create a folder inside your project folder like i did in below screenshot name as images.
  2. Place your image inside images folder.

4. Add View tag in render’s return block.

5. Add TouchableOpacity in render’s return block inside View tag.

6. Add Image tag inside TouchableOpacity block.

7. Create function inside your Main class named as callFun .

8. Add activeOpacity and onPress on TouchableOpacity.

9. Calling callFun function on onPress  on TouchableOpacity.

10. Add Source attribute in Image tag and Assign image path using require.

11. Create StyleSheet just above the AppRegistry.registerComponent line.

12. Inside StyleSheet create two styles Container for complete View and ImageClass for Image.

13. Call css class into both View and Image tag.

14. Complete Source Code for index.android.js file :

Screenshots:

onPress

Leave a Reply

Your email address will not be published. Required fields are marked *