Set onClickListener onPress on Button in React Native Android iOS

How to add onPress to button component in React Native and call a function defined in the same class on button click event using this.

What we are doing in this project : In this tutorial we would going to implement onClick method on Button using onPress. The onPress method works on both android and iOS devices. After setting up onPress we would declare a simple method in our main class. Inside this method we would call a simple Alert message. You can define any task in this method, which you want to complete on button click event.

Contents in this project Set onClickListener onPress on Button :

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

2. Add AppRegistryView, Button, Alert component in import block.

3. declare a function named as SampleFunction() in your main class.

4. Add Singe View as parent view in render’s return block and style it using inline css.

5. Add Button in Parent View.

6. Add onPress on button. We have to call the function with this and dot ( . ) operator. this determines that this function belongs to the same class.

7. Set button Above title text which is shows on button as button Text and button color using style.

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

Screenshots: