Share
Explore

Lab Workbook: Building a Simple Calculator App with React on CodePen.io

Lab Workbook: Building a Simple Calculator App with React on CodePen.io

Introduction
In this lab, we will build a simple calculator app using React.js.
The calculator will perform basic arithmetic operations on floating-point numbers and prevent division by zero.
We will use CodePen.io as our development environment.
Prerequisites
Before we start, make sure you have a basic understanding of:
Understanding of Node application development, and the Node eco system.
JavaScript and React.js.
Familiarity with HTML and CSS.

Step 1: Setting Up the Project on CodePen.io
Go to .
Sign up for a free account if you don't have one.
Click on the "Create" button at the top right corner and select "New Pen".
You will see three sections: HTML, CSS, and JS. We will write our React.js code in the JS section.

Step 2: Importing React and ReactDOM Libraries
In the JS section, click on the settings icon and add the following two URLs in the "Add External Scripts/Pens" field:
https://unpkg.com/react@17/umd/react.development.js
https://unpkg.com/react-dom@17/umd/react-dom.development.js
Step 3: Creating the Calculator Component
In the JS section, we will create a Calculator component. This component will manage the state of our application and render the calculator's interface.
Explainclass Calculator extends React.Component {
constructor(props) {
super(props);
this.state = {
input: '',
result: 0,
};
}

// We will add methods for handling user input and calculations here

render() {
return (
<div className="calculator">
<div className="display">{this.state.result}</div>
<div className="buttons">
{/* We will add buttons here */}
</div>
</div>
);
}
}

ReactDOM.render(<Calculator />, document.getElementById('root'));

Step 4: Adding Buttons
We will add buttons for numbers 0-9, decimal point (.), and arithmetic operations (+, -, *, /). Each button will call a method when clicked, passing its value as an argument.
jsx
Explain// Inside the render method of the Calculator component
<div className="buttons">
{[7, 8, 9, 4, 5, 6, 1, 2, 3, 0, "."].map((num) => (
<button onClick={() => this.handleInput(num)}>{num}</button>
))}
{["+", "-", "*", "/"].map((op) => (
<button onClick={() => this.handleOperation(op)}>{op}</button>
))}
<button onClick={() => this.handleEqual()}>=</button>
<button onClick={() => this.handleClear()}>C</button>
</div>

Step 5: Handling User Input and Calculations
We will add methods to the Calculator component for handling user input and calculations.
jsx
Explain// Inside the Calculator component
handleInput(num) {
this.setState({ input: this.state.input + num });
}

handleOperation(op) {
this.setState({ input: this.state.input + " " + op + " " });
}

handleEqual() {
try {
const result = eval(this.state.input);
if (isFinite(result)) {
this.setState({ result });
} else {
throw new Error("Division by zero is not allowed.");
}
} catch (error) {
this.setState({ result: "Error" });
}
}

handleClear() {
this.setState({ input: '', result: 0 });
}

Step 6: Styling the Calculator
You can add CSS in the CSS section of CodePen.io to style the calculator. Here is a basic example:
.calculator {
width: 200px;
margin: 0 auto;
}

.display {
height: 50px;
background: #eee;
margin-bottom: 10px;
text-align: right;
line-height: 50px;
padding-right: 10px;
}

.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}

button {
height: 50px;
}

Here is the complete code for the Calculator component:

image.png

This code creates a Calculator component that manages the state of the application and renders the calculator's interface. It includes methods for handling user input, performing calculations, and clearing the input and result. The render method returns JSX elements that display the calculator's interface, including buttons for numbers, arithmetic operations, equals, and clear.
Did your code work correctly?



Conclusion
Congratulations! You have built a simple calculator app using React.js on CodePen.io.
You can now experiment with the app, try different calculations, and even add more features if you wish.

Happy coding!


Another version:

Here is a simple calculator application written in React, embedded within an HTML file. This application performs basic operations like addition and subtraction. The JavaScript code is included within the HTML file using the <script> tag:

html<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple React Calculator</title> <script src="https://unpkg.com/react@17/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script></head><body> <div id="root"></div>
<script type="text/babel"> function App() { const [num1, setNum1] = React.useState(0); const [num2, setNum2] = React.useState(0); const [result, setResult] = React.useState(0);
function addNumbers() { setResult(num1 + num2); }
function subtractNumbers() { setResult(num1 - num2); }
return ( <div> <input type="number" value={num1} onChange={e => setNum1(+e.target.value)} /> <input type="number" value={num2} onChange={e => setNum2(+e.target.value)} /> <button onClick={addNumbers}>Add</button> <button onClick={subtractNumbers}>Subtract</button> <h2>Result: {result}</h2> </div> ); }
ReactDOM.render(<App />, document.getElementById('root')); </script></body></html>
This HTML file includes a simple calculator application written in React. The application performs basic operations like addition and subtraction. The JavaScript code is included within the HTML file using the <script> tag. The + operator in the onChange event handlers is used to convert the input values from strings to numbers. The application is rendered in the root div.

Next Version

To create a set of buttons for digits 0-9 and operations for addition and subtraction, you can create two new React components: ButtonDigit and ButtonOperation. These components will render the buttons and handle the click events. Here's how you can modify your existing code to include these components:

htmlExplain<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple React Calculator</title> <script src="https://unpkg.com/react@17/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script></head><body> <div id="root"></div>
<script type="text/babel"> function ButtonDigit({ digit, onClick }) { return <button onClick={() => onClick(digit)}>{digit}</button>; }
function ButtonOperation({ operation, onClick }) { return <button onClick={() => onClick(operation)}>{operation}</button>; }
function App() { const [num1, setNum1] = React.useState(0); const [num2, setNum2] = React.useState(0); const [result, setResult] = React.useState(0);
function addNumbers() { setResult(num1 + num2); }
function subtractNumbers() { setResult(num1 - num2); }
return ( <div> <input type="number" value={num1} onChange={e => setNum1(+e.target.value)} /> <input type="number" value={num2} onChange={e => setNum2(+e.target.value)} /> {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(digit => ( <ButtonDigit digit={digit} onClick={setNum1} /> ))} <ButtonOperation operation="+" onClick={addNumbers} /> <ButtonOperation operation="-" onClick={subtractNumbers} /> <h2>Result: {result}</h2> </div> ); }
ReactDOM.render(<App />, document.getElementById('root')); </script></body></html>
In this code, ButtonDigit and ButtonOperation are functional components that render a button with a specific digit or operation. When the button is clicked, it calls the onClick prop with the digit or operation as an argument. In the App component, we use these components to render the calculator buttons. We use the map function to create a ButtonDigit for each digit from 0 to 9. We also create two ButtonOperation components for the addition and subtraction operations
.


Calculator Version 3:
Based on your request, here is the content you should put into the src/App.js file in your React project to properly handle the Babel transpilation for JSX syntax:
jsx
import React from 'react';

function ButtonDigit({ digit, onClick }) {
return <button onClick={onClick}>{digit}</button>;
}

function Calculator() {
const [display, setDisplay] = React.useState("");

const handleClick = (digit) => {
setDisplay(display + digit);
};

const handleClear = () => {
setDisplay("");
};

const handleCalculate = () => {
try {
setDisplay(eval(display).toString());
} catch {
setDisplay("Error");
}
};

return (
<div>
<div>{display}</div>
<div>
{Array.from({ length: 10 }, (_, i) => (
<ButtonDigit digit={i} onClick={() => handleClick(i)} />
))}
<button onClick={handleClear}>C</button>
<button onClick={() => handleClick("+")}>+</button>
<button onClick={() => handleClick("-")}>-</button>
<button onClick={handleCalculate}>=</button>
</div>
</div>
);
}

export default Calculator;
This code defines a ButtonDigit component that renders a button for each digit. The Calculator component maintains the current display as state and updates it when a button is clicked. The handleClick function appends the clicked digit to the current display. The handleClear function resets the display to an empty string. The handleCalculate function evaluates the current display as a JavaScript expression and updates the display with the result. If the expression is invalid, it sets the display to "Error".
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.