Share
Explore

Project Calculator: REACT.js

Learning Outcome:
Properly handling the Babel transpilation for JSX syntax.
Use the create-react-app package to set up a development environment for your React application.
Follow these steps to set up a new React project using create-react-app:
Open a terminal or command prompt.
Run the following command to install create-react-app globally:
bash
npm install -g create-react-app

Create a new React project using the following command:
bash
create-react-app my-calculator

Replace my-calculator with the desired name for your project.
Change to the newly created project directory:
bash
cd my-calculator
Replace the contents of the src/App.js file with the code from your calculator application.
Start the development server using the following command:
bash
npm start
This command will start a development server, and your React application should now be accessible at http://localhost:3000 in your web browser.

Replace the contents of the src/App.js file in your React project with the calculator code.
Here's the content you should put into the src/App.js file:

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"
.

To work with the provided App.js file, you can create an index.html file and an index.js file. The index.html file will contain the basic structure of the HTML page, and the index.js file will render the Calculator component from the App.js file.

Here's the content for the index.html file:
<!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>
</head>
<body>
<div id="root"></div>
<script src="index.js"></script>
</body>
</html>

And here's the content for the index.js file:

import React from 'react';
import ReactDOM from 'react-dom';
import Calculator from './App';

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

Make sure to place the index.html and index.js files in the same directory as the App.js file.
The index.js file imports the Calculator component from the App.js file and renders it inside the root div in the index.html file.

run npm start in the terminal to start your App
image.png
image.png
Now rework this code to present the key pad in a 4 x 4 matrix
Extend to include multiple and divide
Do not let user try to divide by zero


Exercise Version 5:

New component Button.js

import React from 'react';


function Button({ value, onClick }) {
return (
<button className="button" onClick={onClick}>
{value}
</button>
);
}

export default Button;

Make a component called Calculator.js

import React, { useState } from 'react';

import Button from './Button';

function Calculator() {
const [output, setOutput] = useState("");
const buttons = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "+", "-", "*", "/", "="];
const handleClick = (value) => {
if (value === "=") {
try {
setOutput(eval(output));
} catch {
setOutput("Error");
}
} else {
setOutput(output + value);
}
};

return (
<div className="calculator">
<div className="output">{output}</div>
<div className="buttons">
{buttons.map((button, index) => (
<Button key={index} value={button} onClick={() => handleClick(button)} />
))}
</div>
</div>
);
}

export default Calculator;

Updated App.js

import React from 'react';

import './App.css';
import Calculator from './Calculator';

function App() {
return (
<div className="App">
<Calculator />
</div>
);
}

export default App;

app.css

.calculator {

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

.output {
grid-column: span 4;
height: 100px;
font-size: 32px;
background-color: #0f1cd1;
display: flex;
align-items: center;
justify-content: center;
}

.button {
padding: 20px;
background-color: #c91212;
border: none;
font-size: 20px;
}


This update provides a Clear Function and prevents division by Zero:

import React, { useState } from 'react';

import Button from './Button';

function Calculator() {
const [output, setOutput] = useState("");

const buttons = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "+", "-", "*", "/", "=", "CLEAR"];

const handleClick = (value) => {
if (value === "=") {
if (output.includes("/0")) {
setOutput("Error: Cannot divide by zero");
} else {
try {
setOutput(eval(output));
} catch {
setOutput("Error");
}
}
} else if (value === "CLEAR") {
setOutput("");
} else {
setOutput(output + value);
}
};

return (
<div className="calculator">
<div className="output">{output}</div>
<div className="buttons">
{buttons.map((button, index) => (
<Button key={index} value={button} onClick={() => handleClick(button)} />
))}
</div>
</div>
);
}

export default Calculator;


Allow decimals but not multiple decimals:

import React, { useState } from 'react';

import Button from './Button';

function Calculator() {
const [output, setOutput] = useState("");

const buttons = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ".", "+", "-", "*", "/", "=", "CLEAR"];

const handleClick = (value) => {
if (value === "=") {
if (output.includes("/0")) {
setOutput("Error: Cannot divide by zero");
} else {
try {
setOutput(eval(output).toString());
} catch {
setOutput("Error");
}
}
} else if (value === "CLEAR") {
setOutput("");
} else if (value === ".") {
const lastNumber = output.split(/[\+\-\*\/]/).slice(-1)[0];
if (!lastNumber.includes(".")) {
setOutput(output + value);
}
} else {
setOutput(output + value);
}
};

return (
<div className="calculator">
<div className="output">{output}</div>
<div className="buttons">
{buttons.map((button, index) => (
<Button key={index} value={button} onClick={() => handleClick(button)} />
))}
</div>
</div>
);
}

export default Calculator;
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.