Create Your Calculator App in React Native in 2 hours – [Part 2]

React Native Calculator App [Part 2]

Hello friends, we are back with the final part of this tutorial series i.e create your calculator app in react native in 2 hours.

if you missed the part 1 of this tutorial series then click on below link to read that first awesome article on How to Create Your Calculator App in React Native in 2 hours – [Part 1]

so now I am going to discuss about rest 2 components of this calculator app so that your app will be completed and you can run and test this app in your IOS and Android devices.

so without wasting time let’s jump to our 3rd component for this app i.e Calculator Response (.js)

  • CalculatorResponse.js – 

This file is to show the calculator response on screen. i.e this screen contains the view for showing results from calculations. we have a main view inside which we have a results showing view. on which we are showing digits generated from response from operations.

also we have a Clear (AC) button to clear the input field and all calculations. this AC Text is inside touchable opacity to make it clickable with button feel.

also in addition we have a <Text></Text> for label.

here is the code for CalculatroResponse.js file –

import React from 'react';
import {View, Text, StyleSheet, TouchableOpacity} from 'react-native';

class CalculatorResponse extends React.Component {
    render() {
        const {result, refresh} = this.props;

        return (
            <View>
                <View style={styles.resultContainer}>
                    <Text style={styles.result}>
                        {result}
                    </Text>
                </View>

                <View style={styles.inputContainer}>
                    <TouchableOpacity onPress={refresh}>
                        <Text style={styles.delete}>
                            {/* ⏎ */}
                            AC
                        </Text>
                    </TouchableOpacity>

                    <Text style={styles.input}>
                        Enter your operation
                    </Text>
                </View>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    resultContainer: {
        alignItems: 'flex-end',
        backgroundColor: 'rgba(255, 255, 255, 0.1)',
        marginTop: 25,
        paddingVertical: 25,
        paddingRight: 10,
        margin: 1
    },

    result: {
        color: '#fff',
        fontSize: 42
    },

    inputContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        backgroundColor: 'rgba(255, 255, 255, 0)',
        paddingVertical: 10,
        paddingHorizontal: 5
    },

    delete: {
        color: 'rgba(255, 255, 255, 0.5)',
        fontSize: 23,
        paddingVertical: 5,
        paddingHorizontal: 10
    },

    input: {
        color: 'rgba(255, 255, 255, 0.9)',
        fontSize: 23,
        padding: 5
    }
});

export default CalculatorResponse;

so now we have completed our basic components of Calculator app. finally we need to wrap all the components to make it work like a real calculator. so we will do this in our App.js which acts as our 4th component for this Calculator App.

App.js is our entry point for our application or we can say it is the very first screen / component loaded in our app so we will bind all other 3 components in our App.js file to make it work.

 

  • App.js – 

Here in app.js we have handled our button press function with reset function to make our calculator work.

in UI / Component / Render part of App.js we have a parent component LinearGradient which is a library for react native to make Gradient background in our app. this is a good library if you want to have a gradient background for your app to make it look good.

inside LinearGradient  we have <CalculatorResponse> element which is wrapping our <CalculatorButtonsContainer> element. also we have used StatusBar component from react-native.

so take a look at code for App.js –

import React, {Component} from 'react';
import {Alert, StyleSheet, StatusBar, BackAndroid} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import CalculatorResponse from './components/calculatorresponse';
import CalculatorButtonsContainer from './components/calculatorbuttonscontainer';

export default class App extends Component < {} > {
  constructor() {
    super();

    this.state = {
      result: 0
    };
  }
  componentDidMount() {
    BackAndroid.addEventListener('hardwareBackPress', this.onBackPress);
  }

  onBackPress() {
    Alert.alert('Confirm Exit', 'Do you want to quit Calculator?', [
      {
        text: 'Cancel',
        onPress: () => console.log('Cancel Pressed!')
      }, {
        text: 'OK',
        onPress: () => BackAndroid.exitApp()
      }
    ])
    return true
  }

  componentWillUnmount() {
    BackAndroid.removeEventListener('hardwareBackPress', this.onBackPress)
  }

  refresh() {
    this.setState({result: 0});
  }

  handleButtonPress(button) {
    debugger
    let oldinput = this.state.result,
      lastLetter;
    if (oldinput == 0) {
      oldinput = '';
    }

    switch (button) {
      case '0':
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
      case '8':
      case '9':
        this.setState({
          result: oldinput + button
        });
        break;
      case "+":
      case "-":
      case "x":
      case "/":
        lastLetter = oldinput.slice(-1);
        if (lastLetter === '+' || lastLetter === '-' || lastLetter === '*' || lastLetter === '/') 
          this.setState({
            result: oldinput.slice(0, -1) + button
          });
        else 
          this.setState({
            result: oldinput + button
          });
        break;
      case '=':
        try {
          this.setState({
            result: eval(this.state.result) + ''
          });
        } catch (e) {
          this.setState({result: 'NaN'});
        }
        break;
      case '.':
        lastLetter = oldinput.slice(-1);
        if (lastLetter !== '.') {
          this.setState({
            result: oldinput + button
          });
        }
        break;
    }
  }

  render() {
    const {result} = this.state;

    return (
      <LinearGradient colors={['#3498db', '#8e44ad']} style={styles.container}>

        <CalculatorResponse
          result={result}
          refresh={this
          .refresh
          .bind(this)}/>

        <CalculatorButtonsContainer
          handleButtonPress={this
          .handleButtonPress
          .bind(this)}/>

        <StatusBar barStyle="light-content"/>
      </LinearGradient>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  }
});

in addition to simple handling we have also handled back press for our app for Android devices.

to handle hardware back press we have registered our backHandler function in will mount and removed this listener on unmount to prevent unnecessary handling of functions when not needed.

so we have completed our all four components now try running your app in ios or android device in release mode and test.

CodingIsEasy Calculator App React Native

CodingIsEasy Calculator App React Native

so our final app will look like above if everything working fine.

if any query regarding code you can comment down below. keep sharing our content and spread knowledge and love.


Happy Coding

You may also like...

3 Responses

  1. Jessiecus says:

    Hello,

    Download Music FLAC Scene Releases: https://0daymusic.org
    Label, LIVESETS, Music Videos.
    Download Dance, Electro, House, Techno, Trance, Pop, Rock, Rap…

    Best regards,
    0day MP3s

  2. Andreaevogy says:

    Hello,

    Download Music Scene Releases: http://0daymusic.org/premium.php
    Server’s capacity 186 TB Music
    Support for FTP, FTPS, SFTP, HTTP, HTTPS.
    Download Dance, Electro, House, Techno, Trance, Pop, Rock, Rap…

    Best regards,
    0day MP3s

  1. March 24, 2018

    […] Create Your Calculator App in React Native in 2 hours – [Part 2]  […]

Leave a Reply to Jessiecus Cancel reply

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