Home >Web Front-end >JS Tutorial >ReactJS |Simple React Calculator
This article will guide you through the process of creating a functional, user-friendly calculator using ReactJS. We'll cover the essential concepts like state management, event handling, and component structure to make this project accessible to beginners and a great learning experience for those familiar with React.
Project Setup
Create a New React App:
Start by setting up a new React project using Create React App:
npx create-react-app react-calculator
cd react-calculator
content_copy
Use code with caution.
Bash
Start the Development Server:
Run the following command to launch your development server:
npm start
content_copy
Use code with caution.
Bash
Your React app will be accessible at http://localhost:3000/.
Component Structure
We'll structure our calculator using a single component: App.js. This component will handle the entire calculator's logic and rendering.
App.js (Main Component)
import React, { useState } from "react";
import "./App.css";
function App() {
const [displayValue, setDisplayValue] = useState("0");
const [operator, setOperator] = useState(null);
const [firstOperand, setFirstOperand] = useState(null);
// Function to handle number button clicks
const handleNumberClick = (number) => {
if (displayValue === "0") {
setDisplayValue(number.toString());
} else {
setDisplayValue(displayValue + number.toString());
}
};
// Function to handle operator button clicks
const handleOperatorClick = (op) => {
setOperator(op);
setFirstOperand(parseFloat(displayValue));
setDisplayValue("0");
};
// Function to handle equals button click
const handleEqualsClick = () => {
const secondOperand = parseFloat(displayValue);
let result;
switch (operator) { case "+": result = firstOperand + secondOperand; break; case "-": result = firstOperand - secondOperand; break; case "*": result = firstOperand * secondOperand; break; case "/": if (secondOperand === 0) { result = "Error"; } else { result = firstOperand / secondOperand; } break; default: result = "Invalid Operation"; } setDisplayValue(result.toString()); setOperator(null); setFirstOperand(null);
};
// Function to handle clear button click
const handleClearClick = () => {
setDisplayValue("0");
setOperator(null);
setFirstOperand(null);
};
return (
{/* Button grid for calculator functions */} <div className="buttons"> <button onClick={() => handleNumberClick("7")}>7</button> <button onClick={() => handleNumberClick("8")}>8</button> <button onClick={() => handleNumberClick("9")}>9</button> <button onClick={() => handleOperatorClick("/")}>/</button> <button onClick={() => handleNumberClick("4")}>4</button> <button onClick={() => handleNumberClick("5")}>5</button> <button onClick={() => handleNumberClick("6")}>6</button> <button onClick={() => handleOperatorClick("*")}>*</button> <button onClick={() => handleNumberClick("1")}>1</button> <button onClick={() => handleNumberClick("2")}>2</button> <button onClick={() => handleNumberClick("3")}>3</button> <button onClick={() => handleOperatorClick("-")}>-</button> <button onClick={() => handleNumberClick("0")}>0</button> <button onClick={() => handleNumberClick(".")}>.</button> <button onClick={() => handleEqualsClick()}>=</button> <button onClick={() => handleOperatorClick("+")}>+</button> <button onClick={() => handleClearClick()}>C</button> </div> </div>
);
}
export default App;
content_copy
Use code with caution.
JavaScript
Explanation
State Management:
We use useState hooks to manage the calculator's state. displayValue holds the current value displayed, operator stores the selected operation, and firstOperand saves the first number entered.
Event Handling:
Functions like handleNumberClick, handleOperatorClick, handleEqualsClick, and handleClearClick handle user interactions with the buttons.
Component Composition:
The App component is responsible for both the logic and the rendering of the calculator, demonstrating how components can combine functionality and presentation.
Adding Styling (App.css)
.calculator {
display: flex;
flex-direction: column;
width: 300px;
border: 1px solid #ccc;
padding: 20px;
border-radius: 5px;
}
.display {
height: 50px;
background-color: #eee;
font-size: 24px;
text-align: right;
padding: 10px;
border-radius: 5px;
margin-bottom: 10px;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 10px;
}
button {
padding: 10px;
border: none;
border-radius: 5px;
background-color: #f0f0f0;
font-size: 18px;
cursor: pointer;
}
button:hover {
background-color: #ddd;
}
content_copy
Use code with caution.
Css
Conclusion
By following these steps, you've created a fully functional calculator using React! This project serves as a great foundation for further exploration of React's capabilities. You can now add features like advanced operations, memory functions, or even a visual theme. Experiment and have fun!
The above is the detailed content of ReactJS |Simple React Calculator. For more information, please follow other related articles on the PHP Chinese website!