Saturday, July 14, 2018

Set Button onPress Event In React Native

In this tutorial, We are going to explain how to set button onPress Event in react native application. A basic button component that should render nicely on any platform. Supports a minimal level of customization. In this demo we are applied onPress Event on button and calling buttonClickListener() function, when user clicks on button.

Set Button onPress Event In React Native


React Native Button onPress

Lets see the below source code that helps, you to bind an event on button, when user clicks on it.

App.js
This is a main Component where we have bind onPress Event on button.  Follow the below steps, that helps to configure onPress event on button.

1. Add Button Component in import  block.
import {
 Platform,
 StyleSheet,
 Text,
 View,
 Button
} from 'react-native';

2. Add Button tag in render’s return block.
  • onPress event is fired, when the user clicks on button. In this case it will call the buttonClickListener() function.
  • title : Set the button title or name.
  • color : Set the button color.

<Button
 onPress={this.buttonClickListener}
 title="Click ME"
 color="#00B0FF"   
/> 

3. Binding an event to class.
//Binding the function with class
buttonClickListener = () =>{
  alert("Clicked On Button !!!");
}


Complete Source Code for App.js

import React, { Component } from "react";
import { Platform, StyleSheet, Text, View, Button } from "react-native";

export default class App extends Component {
  //Binding the function with class
  buttonClickListener = () => {
    alert("Clicked On Button !!!");
  };

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.headerText}>
          React Native Button Onpress Event.
        </Text>

        <Button
          onPress={this.buttonClickListener}
          title="Click ME"
          color="#00B0FF"
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  },
  headerText: {
    fontSize: 20,
    textAlign: "center",
    margin: 10,
    fontWeight: "bold"
  }


Screenshot :
Set Button onPress Event In React Native
 Set Button onPress Event In React Native


Download Link :
https://github.com/skptricks/React-Native/tree/master/Set%20Button%20onPress%20Event%20In%20React%20Native

Video Link :






1 comment: