Sure! I can help you remake your calculator project using React.js. We'll transform your existing HTML, CSS, and JavaScript code into a React application.
Here's how we'll proceed:
- Set Up a New React App: We'll use
create-react-app to bootstrap a new React project.
- Create a Calculator Component: We'll create a
Calculator component that replicates your calculator UI and functionality.
- Implement State and Event Handlers: We'll use React's state and event handling to manage the calculator's operations.
Let's get started!
Step 1: Set Up a New React App
First, make sure you have Node.js and npm installed. Then, open your terminal and run:
npx create-react-app my-calculator
cd my-calculator
This will create a new React application named my-calculator.
Step 2: Create the Calculator Component
We'll create a new component called Calculator.js inside the src directory.
src/Calculator.js
import React, { useState } from 'react';
import './Calculator.css';
const Calculator = () => {
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('');
// ... (We'll add the event handlers and functions here)
return (
<div className="calculator">
<div className="calculator-previous">{previousCalculation}</div>
<input
type="text"
className="calculator-screen"
value={currentInput}
disabled
/>
<div className="calculator-keys">
{/* First row */}
<button onClick={() => resetCalculator()} className="all-clear">AC</button>
<button onClick={() => inputPercent()}>%</button>
<button onClick={() => handleOperator('/')} className="operator">÷</button>
<button onClick={() => backspace()} className="backspace">⌫</button>
{/* Second row */}
<button onClick={() => inputNumber('7')}>7</button>
<button onClick={() => inputNumber('8')}>8</button>
<button onClick={() => inputNumber('9')}>9</button>
<button onClick={() => handleOperator('*')} className="operator">×</button>
{/* Third row */}
<button onClick={() => inputNumber('4')}>4</button>
<button onClick={() => inputNumber('5')}>5</button>
<button onClick={() => inputNumber('6')}>6</button>
<button onClick={() => handleOperator('-')} className="operator">−</button>
{/* Fourth row */}
<button onClick={() => inputNumber('1')}>1</button>
<button onClick={() => inputNumber('2')}>2</button>
<button onClick={() => inputNumber('3')}>3</button>
<button onClick={() => handleOperator('+')} className="operator">+</button>
{/* Fifth row */}
<button onClick={() => inputNumber('0')}>0</button>
<button onClick={() => inputDecimal('.')}>.</button>
<button onClick={() => saveNumber()} className="save">Save</button>
<button onClick={() => calculate()} className="equal-sign operator">=</button>
</div>
</div>
);
};
export default Calculator;
Step 3: Implement State and Event Handlers
Now, let's add the functions and event handlers to manage the calculator's logic.
Add the Event Handler Functions
// Helper function to round results
const roundResult = (number) => {
return parseFloat(number.toFixed(10));
};
// Function to update the input number
const inputNumber = (number) => {
if (waitingForSecondOperand) {
setCurrentInput(number);
setWaitingForSecondOperand(false);
} else {
setCurrentInput(currentInput === '0' ? number : currentInput + number);
}
};
// Function to input a decimal point
const inputDecimal = (dot) => {
if (waitingForSecondOperand) {
setCurrentInput('0.');
setWaitingForSecondOperand(false);
return;
}
if (!currentInput.includes(dot)) {
setCurrentInput(currentInput + dot);
}
};
// Function to handle operators
const handleOperator = (nextOperator) => {
const inputValue = parseFloat(currentInput);
if (operator && waitingForSecondOperand) {
setOperator(nextOperator);
return;
}
if (previousInput === '') {
setPreviousInput(inputValue);
} else if (operator) {
let result = performCalculation[operator](previousInput, inputValue);
result = roundResult(result);
setCurrentInput(String(result));
setPreviousInput(result);
}
setOperator(nextOperator);
setWaitingForSecondOperand(true);
};
// Object to map operators to calculation functions
const performCalculation = {
'+': (firstOperand, secondOperand) => firstOperand + secondOperand,
'-': (firstOperand, secondOperand) => firstOperand - secondOperand,
'*': (firstOperand, secondOperand) => firstOperand * secondOperand,
'/': (firstOperand, secondOperand) => firstOperand / secondOperand,
};
// Function to calculate the result
const calculate = () => {
const inputValue = parseFloat(currentInput);
if (operator && !waitingForSecondOperand) {
let result = performCalculation[operator](previousInput, inputValue);
result = roundResult(result);
setPreviousCalculation(`${previousInput} ${operator} ${inputValue} =`);
setCurrentInput(String(result));
setPreviousInput('');
setOperator(null);
setWaitingForSecondOperand(false);
}
};
// Function to reset the calculator
const resetCalculator = () => {
setCurrentInput('0');
setPreviousInput('');
setOperator(null);
setWaitingForSecondOperand(false);
setPreviousCalculation('');
};
// Function to handle backspace
const backspace = () => {
if (currentInput.length > 1) {
setCurrentInput(currentInput.slice(0, -1));
} else {
setCurrentInput('0');
}
};
// Function to handle percentage calculations
const inputPercent = () => {
const value = parseFloat(currentInput);
const result = value / 100;
setCurrentInput(String(roundResult(result)));
};
// Function to save and recall numbers
const saveNumber = () => {
if (savedNumber === null) {
// Save the current number
setSavedNumber(parseFloat(currentInput));
setPreviousCalculation(`Saved: ${currentInput}`);
} else {
// Recall the saved number
if (waitingForSecondOperand) {
setPreviousInput(savedNumber);
setWaitingForSecondOperand(false);
} else {
setCurrentInput(String(savedNumber));
}
setPreviousCalculation(`Recalled: ${savedNumber}`);
}
};
Step 4: Update the CSS Styles
Create a Calculator.css file in the src directory and paste your CSS code.
src/Calculator.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;
}
Make sure to import this CSS file in your Calculator.js:
import './Calculator.css';
Step 5: Update App.js
Now, open App.js and replace its content with:
src/App.js
import React from 'react';
import Calculator from './Calculator';
function App() {
return (
<div>
<Calculator />
</div>
);
}
export default App;
Step 6: Run the Application
Save all the files and run the application:
npm start
Open your browser and navigate to http://localhost:3000 to see your React calculator in action!
Full Source Code
For your reference, here is the full source code.
src/Calculator.js
import React, { useState } from 'react';
import './Calculator.css';
const Calculator = () => {
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('');
// Helper function to round results
const roundResult = (number) => {
return parseFloat(number.toFixed(10));
};
// Function to update the input number
const inputNumber = (number) => {
if (waitingForSecondOperand) {
setCurrentInput(number);
setWaitingForSecondOperand(false);
} else {
setCurrentInput(currentInput === '0' ? number : currentInput + number);
}
};
// Function to input a decimal point
const inputDecimal = (dot) => {
if (waitingForSecondOperand) {
setCurrentInput('0.');
setWaitingForSecondOperand(false);
return;
}
if (!currentInput.includes(dot)) {
setCurrentInput(currentInput + dot);
}
};
// Function to handle operators
const handleOperator = (nextOperator) => {
const inputValue = parseFloat(currentInput);
if (operator && waitingForSecondOperand) {
setOperator(nextOperator);
return;
}
if (previousInput === '') {
setPreviousInput(inputValue);
} else if (operator) {
let result = performCalculation[operator](previousInput, inputValue);
result = roundResult(result);
setCurrentInput(String(result));
setPreviousInput(result);
}
setOperator(nextOperator);
setWaitingForSecondOperand(true);
};
// Object to map operators to calculation functions
const performCalculation = {
'+': (firstOperand, secondOperand) => firstOperand + secondOperand,
'-': (firstOperand, secondOperand) => firstOperand - secondOperand,
'*': (firstOperand, secondOperand) => firstOperand * secondOperand,
'/': (firstOperand, secondOperand) => firstOperand / secondOperand,
};
// Function to calculate the result
const calculate = () => {
const inputValue = parseFloat(currentInput);
if (operator && !waitingForSecondOperand) {
let result = performCalculation[operator](previousInput, inputValue);
result = roundResult(result);
setPreviousCalculation(`${previousInput} ${operator} ${inputValue} =`);
setCurrentInput(String(result));
setPreviousInput('');
setOperator(null);
setWaitingForSecondOperand(false);
}
};
// Function to reset the calculator
const resetCalculator = () => {
setCurrentInput('0');
setPreviousInput('');
setOperator(null);
setWaitingForSecondOperand(false);
setPreviousCalculation('');
};
// Function to handle backspace
const backspace = () => {
if (currentInput.length > 1) {
setCurrentInput(currentInput.slice(0, -1));
} else {
setCurrentInput('0');
}
};
// Function to handle percentage calculations
const inputPercent = () => {
const value = parseFloat(currentInput);
const result = value / 100;
setCurrentInput(String(roundResult(result)));
};
// Function to save and recall numbers
const saveNumber = () => {
if (savedNumber === null) {
// Save the current number
setSavedNumber(parseFloat(currentInput));
setPreviousCalculation(`Saved: ${currentInput}`);
} else {
// Recall the saved number
if (waitingForSecondOperand) {
setPreviousInput(savedNumber);
setWaitingForSecondOperand(false);
} else {
setCurrentInput(String(savedNumber));
}
setPreviousCalculation(`Recalled: ${savedNumber}`);
}
};
return (
<div className="calculator">
<div className="calculator-previous">{previousCalculation}</div>
<input
type="text"
className="calculator-screen"
value={currentInput}
disabled
/>
<div className="calculator-keys">
{/* First row */}
<button onClick={() => resetCalculator()} className="all-clear">AC</button>
<button onClick={() => inputPercent()}>%</button>
<button onClick={() => handleOperator('/')} className="operator">÷</button>
<button onClick={() => backspace()} className="backspace">⌫</button>
{/* Second row */}
<button onClick={() => inputNumber('7')}>7</button>
<button onClick={() => inputNumber('8')}>8</button>
<button onClick={() => inputNumber('9')}>9</button>
<button onClick={() => handleOperator('*')} className="operator">×</button>
{/* Third row */}
<button onClick={() => inputNumber('4')}>4</button>
<button onClick={() => inputNumber('5')}>5</button>
<button onClick={() => inputNumber('6')}>6</button>
<button onClick={() => handleOperator('-')} className="operator">−</button>
{/* Fourth row */}
<button onClick={() => inputNumber('1')}>1</button>
<button onClick={() => inputNumber('2')}>2</button>
<button onClick={() => inputNumber('3')}>3</button>
<button onClick={() => handleOperator('+')} className="operator">+</button>
{/* Fifth row */}
<button onClick={() => inputNumber('0')}>0</button>
<button onClick={() => inputDecimal('.')}>.</button>
<button onClick={() => saveNumber()} className="save">Save</button>
<button onClick={() => calculate()} className="equal-sign operator">=</button>
</div>
</div>
);
};
export default Calculator;
src/Calculator.css
(Same as before.)
src/App.js
(Same as before.)
Conclusion
You've successfully remade your calculator project using React.js! This React version maintains all the functionality of your original calculator, including the previous calculation display, percentage calculations, backspace, and saving numbers.
Feel free to customize and enhance the calculator further, such as adding additional functions or styling.
Let me know if you have any questions or need further assistance!