Calculator

C

You will create a small calculator with React Native and more specially with Expo CLI. In this tutorial you will learn the basics of the React Native development. Application UI will be created with build-in React Native components and styles. React Hooks will be used to handle application state. Created project is tested with a emulator and a real device. To test with emulators you will need to install Android Studio or Xcode.

Install node

You will need to install Node, because it will be used to create React Native applications. You can find Node here: https://nodejs.org/en/download/.

Install Expo CLI

This tutorial will use Expo to create React Native application. You will need to install Expo CLI command line utility. You can follow these instructions Expo Getting Started or commands below.

npm install -g expo-cli

Create a new project

Create a new Expo based React Native project called “Calculator”

expo init Calculator

Now you can select “blank – a minimal app as clean as empty canvas” Git repository will be created and all needed dependecies will be installed.

Run project

To get started go to your project folder and start development server.

cd Calculator
npm start

You can also use: expo start. This will start a development server for you.

Now your development server should be running and ready:

Run app on Expo client in your mobile

Install Expo client app to your iOS or Android phone and connect it to same wireless network as your computer. On Android, use Expo app to scan the QR code to open your project. On iOS, use camera app to scan QR code to open Expo app.

Your app should be running in mobile phone’s Expo application.

Run app on Android or iOS emulator

Use Android Studio or Xcode to launch emulator first and click “Run on Android device/emulator” or “Run on iOS simulator” buttons to launch application to emulator/simulator from your Metro Builder page at your browser.

You can download Android Studio here: Download Android Studio. Read more information about Xcode here: Xcode.

Remember, you will need to install Expo client to your emulator/simulator.

Modify App.js

Open App.js in text editor and edit displayed text line to show “Hello React Native!” text.

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

export default function App() {
  return (
    <View style={styles.container}>
      <Text>Hello React Native!</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Save your changes and application will reload automatically.

One good editor is Visual Studio Code, download it from here: Visual Studio Code.

Add a UI components to the app

This application uses a few basic React Components to build app UI.

Calculator header

Add a style for the header text.

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  calculator: {
    fontSize: 50,
    fontWeight: 'bold',
    marginBottom: 20
  },

Add Text component inside View component in rendering.

// render component
return (
  <View style={styles.container}>
    <Text style={styles.calculator}>Calculator</Text>
  </View>
);

Number inputs

Numbers will be asked using TextInput components.

Add styles for the number components. Components will use flexDirection : row, so they will be side by side.

row: {
  flexDirection: 'row',
  marginTop: 5
},
text: {
  backgroundColor: 'lightgrey',
  justifyContent: 'center',
  padding: 5,
  width:100,
},
textInput: {
  justifyContent: 'center',
  padding: 5,
  borderBottomWidth: 1.0,
  width: 100,
  marginLeft: 5,
}, 

Add below components hierarcy after Text Calculator header component (inside a View root component). Text components will be used to display a normal text and TextInput components to ask a numbers from the user.

<View style={styles.row}>
  <View style={styles.text}>
    <Text>Number 1:</Text>
  </View>
  <View style={styles.textInput}>
    <TextInput placeholder="0" style={{textAlign:'right'}} ></TextInput>
  </View>
</View>
<View style={styles.row}>
  <View style={styles.text}>
    <Text>Number 2:</Text>
  </View>
  <View style={styles.textInput}>
    <TextInput placeholder="0" style={{textAlign:'right'}} ></TextInput>
  </View>
</View>

Calc buttons

User can select calculation by pressing one of the calc buttons.

Add styles for the calc buttons. Buttons will take 200 px width and use justifyContent as space-around, so they will be nicely set side by side.

buttonRow: {
  flexDirection: 'row',
  marginTop: 20,
  marginBottom: 20,
  justifyContent: 'space-around',
  width: 220
}

Add below components hierarcy after above hierarcy set (inside a View root component).

<View style={styles.buttonRow}>
  <Button title="  +  "/>
  <Button title="  -  "/>
  <Button title="  *  "/>
  <Button title="  /  "/>
</View>

Result

Add below components hierarchy after above one (inside View root component). TextInput component’s editableattribute is set to false, so it only displays a result and it can’t be edited.

<View style={styles.row}>
  <View style={styles.text}>
    <Text>Result:</Text>
  </View>
  <View style={styles.textInput}>
    <TextInput placeholder="0" style={{textAlign:'right'}} editable={false}></TextInput>
  </View>
</View>

Test UI

UI should be now ready. Save your code and test.

Calculation

Get numbers

You can use React Hooks to get numbers from TextInput components. Declare a new state variable for numbers and result.

export default function App() {
  // use hooks to change number values
  const [number1, setNumber1] = useState('0');
  const [number2, setNumber2] = useState('0');
  const [result, setResult] = useState('0');
  ...

Now you have setNumber1 function to change the state of number1 variable, default state is ‘0’. Edit TextInput component to listen onChangeText event to call above React Hook.

<TextInput value={number1} 
  onChangeText={text => setNumber1(text)} 
  style={{textAlign:'right'}} 
  keyboardType={'numeric'}></TextInput>

TextInput can display only numbers with numeric settings.

Do the same for the number2.

Calculate a sum

Add a onPress event handling for all the Button components.

<Button title="  +  " onPress={(e) => buttonPressed(e,'+')}/>
<Button title="  -  " onPress={(e) => buttonPressed(e,'-')}/>
<Button title="  *  " onPress={(e) => buttonPressed(e,'*')}/>
<Button title="  /  " onPress={(e) => buttonPressed(e,'/')}/>

All the button’s event handling will call the same buttonPressed function. Now a different parameters will be passed to the function to detect correct calculation. Add a below buttonPressed function to your app. This function will check, which calculation is pressed and calc a correct new result. Opened keyboard will be dismissed with dismiss function call. Remember import Keyboard to your code.

// button pressed - calculate
const buttonPressed = (e,calc) => {
  if (calc === '+') setResult(parseInt(number1) + parseInt(number2)+"");
  else if (calc === '-') setResult(parseInt(number1) - parseInt(number2)+"");
  else if (calc === '/') setResult(parseInt(number1) / parseInt(number2)+"");
  else if (calc === '*') setResult(parseInt(number1) * parseInt(number2)+"");
  Keyboard.dismiss();
}

Result

Remember edit result TextInput to show the calculation result.

<View style={styles.textInput}>
  <TextInput placeholder="0" 
             value={result} 
             style={{textAlign:'right'}} 
             editable={false}></TextInput>
</View>

Test

Test your application. It should work now.

Add comment

Pasi Manninen

Pasi Manninen

Pasi is a mobile and web application developer. Currently working as a senior lecturer in JAMK University of Applied Sciences. Pasi has programming experience over many decades and has taught dozens of courses since the 90's.

Recent Posts

Follow Me