Building a Simple Calculator App Using React Native in 2024
React Native is a popular framework for building mobile applications using JavaScript and leveraging the power of React. In this blog post, we will walk through the process of creating a simple calculator app using React Native. This calculator will be able to perform basic arithmetic operations like addition, subtraction, multiplication, and division.
Prerequisites
Before we start, make sure you have the following installed on your system:
- Node.js and npm (Node Package Manager)
- React Native CLI (Command Line Interface)
- A code editor (like Visual Studio Code)
- An emulator or a real device to run the app (like Android Studio for Android emulation)
Step-by-Step Guide
Step 1: Setting Up the Project
First, we need to set up a new React Native project. Open your terminal and run the following command:
npx react-native init CalculatorApp
This command creates a new directory named CalculatorApp
with all the necessary files and folders for a React Native application.
Step 2: Creating the Calculator Layout
Next, let’s create the layout for our calculator. We’ll need a display area for the calculations and buttons for the digits and operations. Here’s a simple layout:
{ return ( 0 {}} /> {/* Add more buttons */} ); }; export default Calculator; “>
import React from 'react';
import { View, Text, Button } from 'react-native';
const Calculator = () => {
return (
<View>
<View>
<Text>0</Text>
</View>
<View>
<Button title="1" onPress={() => {}} />
{/* Add more buttons */}
</View>
</View>
);
};
export default Calculator;
Step 3: Adding Functionality
Now, let’s add functionality to our calculator. We’ll need to update the display when a button is pressed and perform the calculations when an operation button is pressed.
import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';
const Calculator = () => {
const [display, setDisplay] = useState('0');
const [operand, setOperand] = useState(null);
const [operator, setOperator] = useState(null);
const pressButton = (value) => {
if (display === '0') {
setDisplay(value);
} else {
setDisplay(display + value);
}
};
const pressOperator = (operation) => {
setOperand(parseFloat(display));
setOperator(operation);
setDisplay('0');
};
const calculate = () => {
const num = parseFloat(display);
switch (operator) {
case '+':
setDisplay((operand + num).toString());
break;
case '-':
setDisplay((operand - num).toString());
break;
case '*':
setDisplay((operand * num).toString());
break;
case '/':
setDisplay((operand / num).toString());
break;
}
setOperand(null);
setOperator(null);
};
return (
<View>
<View>
<Text>{display}</Text>
</View>
<View>
<Button title="1" onPress={() => pressButton('1')} />
<Button title="2" onPress={() => pressButton('2')} />
<Button title="3" onPress={() => pressButton('3')} />
<Button title="4" onPress={() => pressButton('4')} />
<Button title="5" onPress={() => pressButton('5')} />
<Button title="6" onPress={() => pressButton('6')} />
<Button title="7" onPress={() => pressButton('7')} />
<Button title="8" onPress={() => pressButton('8')} />
<Button title="9" onPress={() => pressButton('9')} />
<Button title="0" onPress={() => pressButton('0')} />
<Button title="+" onPress={() => pressOperator('+')} />
<Button title="-" onPress={() => pressOperator('-')} />
<Button title="*" onPress={() => pressOperator('*')} />
<Button title="/" onPress={() => pressOperator('/')} />
<Button title="=" onPress={calculate} />
</View>
</View>
);
};
export default Calculator;
In this updated code, I’ve added the pressButton
, pressOperator
, and calculate
functions to handle button presses and perform calculations. The pressButton
function updates the display when a digit button is pressed. The pressOperator
function stores the current number and operator when an operator button is pressed. The calculate
function performs the calculation when the equals button is pressed.
I’ve also added more buttons for the digits and operations. Each button uses the onPress
prop to handle button presses. The digit buttons call the pressButton
function with the digit as the argument. The operator buttons call the pressOperator
function with the operator as the argument. The equals button calls the calculate
function.
Step 4: Styling the App
Finally, let’s add some styles to our app to make it look more like a calculator. We will use the StyleSheet
component from React Native to create a style object, which we can then use to style our components.
Here’s the code for the styles:
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
display: {
backgroundColor: '#f5f5f5',
padding: 20,
margin: 20,
borderRadius: 10,
},
displayText: {
fontSize: 24,
color: '#333',
},
buttons: {
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'space-between',
},
});
In this code, we define styles for the container, display, display text, and buttons. The container
style makes the container take up the full screen and centers its children. The display
style adds a background color, padding, margin, and border radius to the display. The displayText
style sets the font size and color of the display text. The buttons
style arranges the buttons in a grid with space between them.
Now, let’s apply these styles to our components:
return (
<View style={styles.container}>
<View style={styles.display}>
<Text style={styles.displayText}>{display}</Text>
</View>
<View style={styles.buttons}>
<Button title="1" onPress={() => pressButton('1')} />
{/* Add more buttons */}
</View>
</View>
);
In this code, we apply the styles to the components using the style
prop. The style
prop accepts a style object, which we get from our styles
object.
Full Code
Here’s the full code for the calculator app:
import React, { useState } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
const Calculator = () => {
const [display, setDisplay] = useState('0');
const [operand, setOperand] = useState(null);
const [operator, setOperator] = useState(null);
const pressButton = (value) => {
if (display === '0') {
setDisplay(value);
} else {
setDisplay(display + value);
}
};
const pressOperator = (operation) => {
setOperand(parseFloat(display));
setOperator(operation);
setDisplay('0');
};
const calculate = () => {
const num = parseFloat(display);
switch (operator) {
case '+':
setDisplay((operand + num).toString());
break;
case '-':
setDisplay((operand - num).toString());
break;
case '*':
setDisplay((operand * num).toString());
break;
case '/':
setDisplay((operand / num).toString());
break;
}
setOperand(null);
setOperator(null);
};
return (
<View style={styles.container}>
<View style={styles.display}>
<Text style={styles.displayText}>{display}</Text>
</View>
<View style={styles.buttons}>
<Button title="1" onPress={() => pressButton('1')} />
<Button title="2" onPress={() => pressButton('2')} />
<Button title="3" onPress={() => pressButton('3')} />
<Button title="4" onPress={() => pressButton('4')} />
<Button title="5" onPress={() => pressButton('5')} />
<Button title="6" onPress={() => pressButton('6')} />
<Button title="7" onPress={() => pressButton('7')} />
<Button title="8" onPress={() => pressButton('8')} />
<Button title="9" onPress={() => pressButton('9')} />
<Button title="0" onPress={() => pressButton('0')} />
<Button title="+" onPress={() => pressOperator('+')} />
<Button title="-" onPress={() => pressOperator('-')} />
<Button title="*" onPress={() => pressOperator('*')} />
<Button title="/" onPress={() => pressOperator('/')} />
<Button title="=" onPress={calculate} />
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
display: {
backgroundColor: '#f5f5f5',
padding: 20,
margin: 20,
borderRadius: 10,
},
displayText: {
fontSize: 24,
color: '#333',
},
buttons: {
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'space-between',
},
});
export default Calculator;
Final Thoughts
Building a simple calculator app is a great way to learn React Native. It covers many fundamental concepts like state management, event handling, and styling. However, this is just the beginning. React Native offers many more features and capabilities that you can explore to build more complex and powerful apps.
I hope you found this guide helpful. Happy coding! 😊
If you’re looking to enable chat, social or live-streaming experiences in your React-Native platform whether it’s through SDK or our Open-source UIKit, Feel free to explore the features Amity offers, If you find that a pre-built solution aligns with your business goals, you can start right now by contacting Amity here!