diff --git a/src/components/calculator.js b/src/components/calculator.js index d71e9a4..86ed315 100644 --- a/src/components/calculator.js +++ b/src/components/calculator.js @@ -1,57 +1,48 @@ -import React from 'react'; +import React, { useState } from 'react'; import './calculator.css'; import calculate from '../logic/calculate'; -class Calculator extends React.Component { - constructor(props) { - super(props); +const Calculator = () => { + const [state, setState] = useState({ + total: 0, + next: null, + operation: null, + }); - this.state = { - total: 0, - next: null, - operation: null, - }; - - this.handleEvent = this.handleEvent.bind(this); - } - - handleEvent = (buttonName) => { - this.setState((state) => calculate(state, buttonName)); + const handleEvent = (e) => { + setState({ ...state, ...calculate(state, e.target.name) }); }; - render() { - const { total, operation, next } = this.state; - return ( -
-

- {total} - {operation} - {next} -

-
- - - - - - - - - - - - - - - - - - - -
+ return ( +
+

+ {state.total} + {state.operation} + {state.next} +

+
+ + + + + + + + + + + + + + + + + + +
- ); - } -} +
+ ); +}; export default Calculator; diff --git a/src/logic/calculate.js b/src/logic/calculate.js index f165411..d28d7a4 100644 --- a/src/logic/calculate.js +++ b/src/logic/calculate.js @@ -91,11 +91,12 @@ export default function calculate(obj, buttonName) { // When the user presses an operation button without having entered // a number first, do nothing. - // if (!obj.next && !obj.total) { - // return {}; - // } + if (!obj.next && !obj.total) { + return {}; + } // User pressed an operation after pressing '=' + if (!obj.next && obj.total && !obj.operation) { return { ...obj, operation: buttonName }; }