Build a Simple Calculator App with React Native

Building mobile apps has never been more accessible thanks to frameworks like React Native. This JavaScript framework, developed by Facebook, enables developers to create cross-platform applications using a single codebase. In this blog, we’ll walk you through building a simple calculator app using React Native. Whether you’re a beginner or looking to brush up on your skills, this guide will help you understand the core concepts and practices of React Native development.

Why Choose React Native?

React Native allows developers to write code once and deploy it across multiple platforms, including iOS and Android. This cross-platform capability is a significant advantage, reducing the time and cost associated with developing separate native apps for different operating systems. Additionally, React Native offers a rich ecosystem of libraries and tools that can accelerate development.

Setting Up Your Development Environment

Before diving into the code, you need to set up your development environment. Here’s a quick overview of the steps:

  1. Install Node.js and npm: React Native relies on Node.js and npm (Node Package Manager). You can download and install them from Node.js official website.

  2. Install Expo CLI: Expo is a set of tools built around React Native that simplifies the development process. Install Expo CLI globally by running the following command:

    bash

    npm install -g expo-cli
  3. Create a New React Native Project: Once Expo CLI is installed, you can create a new project by running:

    bash

    expo init CalculatorApp

    Choose the “blank” template for a clean slate.

  4. Navigate to Your Project Directory: Move into your project folder:

    bash

    cd CalculatorApp
  5. Start the Development Server: Run the following command to start the development server:

    bash

    expo start

Designing the Calculator App

A calculator app typically consists of a display area and a set of buttons for digits and operations. In React Native, you’ll use components to structure your UI. Let’s break down the key components:

  1. Display Component: This component will show the current calculation or result.

  2. Button Component: Each button represents a digit or an operation. You’ll create a reusable button component to keep your code DRY (Don’t Repeat Yourself).

Implementing the Calculator UI

  1. Creating the Display Component

    First, create a file named Display.js in your components folder:

    javascript

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

    const Display = ({ value }) => {
    return (
    <View style={styles.container}>
    <Text style={styles.text}>{value}</Text>
    </View>

    );
    };

    const styles = StyleSheet.create({
    container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'flex-end',
    backgroundColor: '#000',
    padding: 20,
    },
    text: {
    color: '#fff',
    fontSize: 48,
    fontWeight: 'bold',
    },
    });

    export default Display;

  2. Creating the Button Component

    Create a file named Button.js in your components folder:

    javascript

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

    const Button = ({ title, onPress }) => {
    return (
    <TouchableOpacity style={styles.button} onPress={onPress}>
    <Text style={styles.text}>{title}</Text>
    </TouchableOpacity>

    );
    };

    const styles = StyleSheet.create({
    button: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#333',
    margin: 5,
    borderRadius: 5,
    },
    text: {
    color: '#fff',
    fontSize: 24,
    },
    });

    export default Button;

  3. Building the Calculator Layout

    In your App.js, import and use the Display and Button components to create the calculator layout:

    javascript

    import React, { useState } from 'react';
    import { View, StyleSheet, Button } from 'react-native';
    import Display from './components/Display';
    import Button from './components/Button';

    const App = () => {
    const [input, setInput] = useState('');

    const handlePress = (value) => {
    if (value === '=') {
    try {
    setInput(eval(input).toString());
    } catch {
    setInput('Error');
    }
    } else if (value === 'C') {
    setInput('');
    } else {
    setInput(input + value);
    }
    };

    return (
    <View style={styles.container}>
    <Display value={input} />
    <View style={styles.buttons}>
    <View style={styles.row}>
    <Button title="1" onPress={() => handlePress('1')} />
    <Button title="2" onPress={() => handlePress('2')} />
    <Button title="3" onPress={() => handlePress('3')} />
    <Button title="/" onPress={() => handlePress('/')} />
    </View>
    <View style={styles.row}>
    <Button title="4" onPress={() => handlePress('4')} />
    <Button title="5" onPress={() => handlePress('5')} />
    <Button title="6" onPress={() => handlePress('6')} />
    <Button title="*" onPress={() => handlePress('*')} />
    </View>
    <View style={styles.row}>
    <Button title="7" onPress={() => handlePress('7')} />
    <Button title="8" onPress={() => handlePress('8')} />
    <Button title="9" onPress={() => handlePress('9')} />
    <Button title="-" onPress={() => handlePress('-')} />
    </View>
    <View style={styles.row}>
    <Button title="C" onPress={() => handlePress('C')} />
    <Button title="0" onPress={() => handlePress('0')} />
    <Button title="=" onPress={() => handlePress('=')} />
    <Button title="+" onPress={() => handlePress('+')} />
    </View>
    </View>
    </View>

    );
    };

    const styles = StyleSheet.create({
    container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#eee',
    },
    buttons: {
    flex: 3,
    backgroundColor: '#aaa',
    },
    row: {
    flexDirection: 'row',
    },
    });

    export default App;

Testing Your Calculator

To test your calculator app, simply run the development server with:

bash

expo start

This will open a new browser tab with the Expo DevTools, and you can see your app running on an emulator or your physical device using the Expo Go app.

Conclusion

Building a calculator app with React Native is an excellent way to get started with mobile app development. By following this guide, you’ve learned how to set up your development environment, design the UI, and implement the app logic. React Native’s ability to streamline the development process and allow for cross-platform deployment makes it a powerful tool for modern app development.