The current implementation of the calculator is not correct. The plus, minus, multiply, and divide functions are all updating the result state twice, which is not what is intended. Also, the handleChange function is not being used to update the result state.
Here's a corrected implementation of the calculator:
import { useState } from "react";
import "./App.css";
function App() {
const [input1, setInput1] = useState("");
const [input2, setInput2] = useState("");
const [result, setResult] = useState(0);
function handleInput1Change(e) {
setInput1(e.target.value);
}
function handleInput2Change(e) {
setInput2(e.target.value);
}
function handlePlus() {
setResult(Number(input1) + Number(input2));
}
function handleMinus() {
setResult(Number(input1) - Number(input2));
}
function handleMultiply() {
setResult(Number(input1) * Number(input2));
}
function handleDivide() {
setResult(Number(input1) / Number(input2));
}
function handleReset() {
setInput1("");
setInput2("");
setResult(0);
}
return (
<div className="App">
<h1>Simplest Working Calculator</h1>
<form>
<input
type="number"
placeholder="Please type a number"
value={input1}
onChange={handleInput1Change}
/>
<input
type="number"
placeholder="Please type again"
value={input2}
onChange={handleInput2Change}
/>
<h2>Result: {result}</h2>
<p>Choose your choice:</p>
<button type="button" onClick={handlePlus}>
+
</button>
<button type="button" onClick={handleMinus}>
-
</button>
<button type="button" onClick={handleMultiply}>
*
</button>
<button type="button" onClick={handleDivide}>
/
</button>
<button type="button" onClick={handleReset}>
Reset
</button>
</form>
</div>
);
}
export default App;
In this implementation, we have separate state variables for the two input values (input1 and input2) and the result (result). We also have separate functions to handle the changes in the input values (handleInput1Change and handleInput2Change) and the different operations (handlePlus, handleMinus, handleMultiply, and handleDivide). Finally, we have a handleReset function to reset all the state variables to their initial values.