Certainly! Below is the React.js version of your calculator project. We'll break it down step by step, including all the necessary files and explanations to get you started.
Project Setup
First, make sure you have Node.js and npm installed on your machine. Then, create a new React application using Create React App by running the following command:
npx create-react-app react-calculator
Navigate into your project directory:
cd react-calculator
Now, we'll start adding the necessary files and code.
File Structure
Your project structure should look like this:
react-calculator/
├── public/
│ └── index.html
├── src/
│ ├── components/
│ │ └── Calculator.js
│ ├── App.js
│ ├── index.js
│ └── styles.css
├── package.json
└── ...
Source Code
1. index.js
This is the entry point of your React application.
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './styles.css'; // Import the CSS styles
ReactDOM.render(<App />, document.getElementById('root'));
2. App.js
This component wraps your Calculator component.
// src/App.js
import React from 'react';
import Calculator from './components/Calculator';
function App() {
return (
<div className="app">
<Calculator />
</div>
);
}
export default App;
3. Calculator.js
This is the main Calculator component where we handle all the calculator logic using React hooks.
// src/components/Calculator.js
import React, { useState } from 'react';
function Calculator() {
// State variables
const [currentInput, setCurrentInput] = useState('0');
const [previousInput, setPreviousInput] = useState('');
const [operator, setOperator] = useState(null);
const [waitingForSecondOperand, setWaitingForSecondOperand] = useState(false);
const [savedNumber, setSavedNumber] = useState(null);
const [previousCalculation, setPreviousCalculation] = useState('');
// Handle button clicks
const handleButtonClick = (event) => {
const value = event.target.value;
switch (value) {
case '+':
case '-':
case '*':
case '/':
handleOperator(value);
break;
case '=':
calculate();
break;
case 'all-clear':
resetCalculator();
break;
case '.':
inputDecimal(value);
break;
case 'backspace':
backspace();
break;
case '%':
inputPercent();
break;
case 'Save':
saveNumber();
break;
default:
if (Number.isInteger(parseFloat(value))) {
inputNumber(value);
}
}
};
// Functions for handling calculations
const inputNumber = (number) => {
if (waitingForSecondOperand) {
setCurrentInput(number);
setWaitingForSecondOperand(false);
} else {
setCurrentInput(currentInput === '0' ? number : currentInput + number);
}
};
const inputDecimal = (dot) => {
if (waitingForSecondOperand) {
setCurrentInput('0.');
setWaitingForSecondOperand(false);
return;
}
if (!currentInput.includes(dot)) {
setCurrentInput(currentInput + dot);
}
};
const handleOperator = (nextOperator) => {
const inputValue = parseFloat(currentInput);
if (operator && waitingForSecondOperand) {
setOperator(nextOperator);
return;
}
if (previousInput === '') {
setPreviousInput(inputValue);
} else if (operator) {
const result = performCalculation(operator, previousInput, inputValue);
const roundedResult = roundResult(result);
setCurrentInput(String(roundedResult));
setPreviousInput(roundedResult);
}
setOperator(nextOperator);
setWaitingForSecondOperand(true);
};
const performCalculation = (operator, firstOperand, secondOperand) => {
switch (operator) {
case '+':
return firstOperand + secondOperand;
case '-':
return firstOperand - secondOperand;
case '*':
return firstOperand * secondOperand;
case '/':
return firstOperand / secondOperand;
default:
return secondOperand;
}
};
const calculate = () => {
const inputValue = parseFloat(currentInput);
if (operator && !waitingForSecondOperand) {
const result = performCalculation(operator, previousInput, inputValue);
const roundedResult = roundResult(result);
// Store the previous calculation expression
setPreviousCalculation(`${previousInput} ${operator} ${inputValue} =`);
setCurrentInput(String(roundedResult));
setPreviousInput('');
setOperator(null);
setWaitingForSecondOperand(false);
}
};
const resetCalculator = () => {
setCurrentInput('0');
setPreviousInput('');
setOperator(null);
setWaitingForSecondOperand(false);
setPreviousCalculation('');
};
const backspace = () => {
if (currentInput.length > 1) {
setCurrentInput(currentInput.slice(0, -1));
} else {
setCurrentInput('0');
}
};
const inputPercent = () => {
const value = parseFloat(currentInput);
const result = value / 100;
setCurrentInput(String(roundResult(result)));
};
const saveNumber = () => {
if (savedNumber === null) {
// Save the current number
const num = parseFloat(currentInput);
setSavedNumber(num);
setPreviousCalculation(`Saved: ${num}`);
} else {
// Recall the saved number
if (waitingForSecondOperand) {
setPreviousInput(savedNumber);
setWaitingForSecondOperand(false);
} else {
setCurrentInput(String(savedNumber));
}
setPreviousCalculation(`Recalled: ${savedNumber}`);
}
};
const roundResult = (number) => {
return parseFloat(number.toFixed(10));
};
return (
<div className="calculator">
{/* Display for previous calculation */}
<div className="calculator-previous">{previousCalculation}</div>
{/* Display for current input */}
<input
type="text"
className="calculator-screen"
value={currentInput}
disabled
/>
{/* Calculator buttons */}
<div className="calculator-keys">
{/* First row: AC, %, /, backspace */}
<button
type="button"
className="all-clear"
value="all-clear"
onClick={handleButtonClick}
>
AC
</button>
<button type="button" value="%" onClick={handleButtonClick}>
%
</button>
<button
type="button"
className="operator"
value="/"
onClick={handleButtonClick}
>
÷
</button>
<button
type="button"
className="backspace"
value="backspace"
onClick={handleButtonClick}
>
⌫
</button>
{/* Second row: 7, 8, 9, * */}
<button type="button" value="7" onClick={handleButtonClick}>
7
</button>
<button type="button" value="8" onClick={handleButtonClick}>
8
</button>
<button type="button" value="9" onClick={handleButtonClick}>
9
</button>
<button
type="button"
className="operator"
value="*"
onClick={handleButtonClick}
>
×
</button>
{/* Third row: 4, 5, 6, - */}
<button type="button" value="4" onClick={handleButtonClick}>
4
</button>
<button type="button" value="5" onClick={handleButtonClick}>
5
</button>
<button type="button" value="6" onClick={handleButtonClick}>
6
</button>
<button
type="button"
className="operator"
value="-"
onClick={handleButtonClick}
>
−
</button>
{/* Fourth row: 1, 2, 3, + */}
<button type="button" value="1" onClick={handleButtonClick}>
1
</button>
<button type="button" value="2" onClick={handleButtonClick}>
2
</button>
<button type="button" value="3" onClick={handleButtonClick}>
3
</button>
<button
type="button"
className="operator"
value="+"
onClick={handleButtonClick}
>
+
</button>
{/* Fifth row: 0, decimal point, Save, = */}
<button type="button" value="0" onClick={handleButtonClick}>
0
</button>
<button
type="button"
className="decimal"
value="."
onClick={handleButtonClick}
>
.
</button>
<button
type="button"
className="save"
value="Save"
onClick={handleButtonClick}
>
Save
</button>
<button
type="button"
className="equal-sign operator"
value="="
onClick={handleButtonClick}
>
=
</button>
</div>
</div>
);
}
export default Calculator;
4. styles.css
This CSS file styles your calculator to look like the original one.
/* src/styles.css */
/* General Styles */
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f3f3f3;
}
.calculator {
width: 400px;
margin: 100px auto;
border: 1px solid #ccc;
border-radius: 10px;
overflow: hidden;
}
/* Previous Calculation Display */
.calculator-previous {
width: 100%;
height: 40px;
background-color: #1a1a1a;
color: #aaa;
text-align: right;
font-size: 1.5rem;
padding-right: 20px;
padding-left: 10px;
box-sizing: border-box;
overflow: hidden;
}
/* Screen Styles */
.calculator-screen {
width: 100%;
height: 80px;
border: none;
background-color: #252525;
color: #fff;
text-align: right;
font-size: 4rem;
padding-right: 20px;
padding-left: 10px;
box-sizing: border-box;
}
/* Button Styles */
.calculator-keys {
display: grid;
grid-template-columns: repeat(4, 1fr);
}
button {
height: 80px;
font-size: 2rem;
border: 1px solid #ddd;
background-color: #e0e0e0;
color: #333;
cursor: pointer;
}
button:hover {
background-color: #d0d0d0;
}
.operator {
background-color: #ff9500;
color: #fff;
}
.all-clear,
.backspace {
background-color: #ff3b30;
color: #fff;
}
.equal-sign {
background-color: #007aff;
color: #fff;
}
/* Style the "Save" button */
.save {
background-color: #a9a9a9;
color: #fff;
}
Running the Application
After you've added all the files and code, you can run your React application with:
npm start
This will start the development server, and you can view your calculator by navigating to http://localhost:3000/ in your web browser.
Explanation
-
State Management: We use React's useState hook to manage the calculator's state variables, such as currentInput, previousInput, operator, etc.
-
Event Handling: All button clicks are handled by the handleButtonClick function, which delegates actions based on the button's value.
-
Calculation Logic: The functions like handleOperator, calculate, and performCalculation replicate the calculator's logic from your original JavaScript code.
-
Rendering: The calculator UI is built using JSX, which closely resembles your original HTML structure.
Additional Notes
-
CSS Styling: The styles are applied globally via the styles.css file. If you prefer scoped styling, you could use CSS Modules or styled-components.
-
Component Organization: The Calculator component contains all the logic and UI elements. For larger projects, you might consider breaking it down into smaller components.
-
Input Display: The input fields are set to disabled to prevent user input via keyboard, ensuring all interactions go through the buttons.
Feel free to customize and extend the calculator as you see fit. Happy coding!