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 AppRegistry, View, Button, Alert component in import block.
1 |
import { AppRegistry, View, Button, Alert } from 'react-native'; |
3. declare a function named as SampleFunction() in your main class.
1 2 3 4 5 |
TestFunction() { Alert.alert('Button Pressed !!!') } |
4. Add Singe View as parent view in render’s return block and style it using inline css.
1 2 3 4 5 6 7 8 9 |
render() { return ( <View style={{flex :1, justifyContent: 'center', margin: 8 }}> </View> ); } |
5. Add Button in Parent View.
1 2 3 4 5 6 7 8 9 |
render() { return ( <View style={{flex :1, justifyContent: 'center', margin: 8 }}> <Button /> </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.
1 2 3 4 5 |
<View style={{flex :1, justifyContent: 'center', margin: 8 }}> <Button onPress={ this.TestFunction } /> </View> |
7. Set button Above title text which is shows on button as button Text and button color using style.
1 2 3 4 5 |
<View style={{flex :1, justifyContent: 'center', margin: 8 }}> <Button onPress={ this.TestFunction } title="Test Button" color="#009688" /> </View> |
8. Complete Source Code for index.android.js file :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import React, { Component } from 'react'; import { AppRegistry, View, Button, Alert } from 'react-native'; class Myproject extends Component { TestFunction() { Alert.alert('Button Pressed !!!') } render() { return ( <View style={{flex :1, justifyContent: 'center', margin: 8 }}> <Button onPress={ this.TestFunction } title="Test Button" color="#009688" /> </View> ); } } AppRegistry.registerComponent('Myproject', () => Myproject); |
Screenshots: