diff --git a/src/component/App.js b/src/component/App.js index b2b4fec53..bc9fc560e 100644 --- a/src/component/App.js +++ b/src/component/App.js @@ -4,6 +4,7 @@ import ButtonPanel from "./ButtonPanel"; import calculate from "../logic/calculate"; import "./App.css"; + export default class App extends React.Component { state = { total: null, @@ -11,14 +12,43 @@ export default class App extends React.Component { operation: null, }; + constructor(props){ + super(props); + this.inputRef = React.createRef(); //ref to focus master div + } + + componentDidMount(){ + this.inputRef.current.focus(); //focusing master div to listen keyboard press + } + + keyHandler = (e) => { + console.log(e.key); + if(e.key == 0 || e.key == 1 || e.key == 2 || e.key == 3 || e.key == 4 || e.key == 5 || e.key == 6 || e.key == 7 || e.key == 7 || e.key == 8 || e.key == 9 + || e.key == '+' || e.key == '-' || e.key == "%" || e.key == "."){ + this.setState(calculate(this.state, e.key)); + } + else if(e.key == "Enter"){ + this.setState(calculate(this.state, "=")); + } + else if(e.key == "*"){ + this.setState(calculate(this.state, 'x')); + } + else if(e.key == "/"){ + this.setState(calculate(this.state, '÷')); + } + + } + handleClick = buttonName => { this.setState(calculate(this.state, buttonName)); }; + + render() { return ( -
- +
+
); diff --git a/src/component/ButtonPanel.js b/src/component/ButtonPanel.js index 994bca43d..c02988e32 100644 --- a/src/component/ButtonPanel.js +++ b/src/component/ButtonPanel.js @@ -13,6 +13,7 @@ export default class ButtonPanel extends React.Component { this.props.clickHandler(buttonName); }; + render() { return (
diff --git a/src/logic/operate.js b/src/logic/operate.js index 0274e3a74..a763ec90c 100644 --- a/src/logic/operate.js +++ b/src/logic/operate.js @@ -13,7 +13,7 @@ export default function operate(numberOne, numberTwo, operation) { return one.times(two).toString(); } if (operation === "÷") { - if (two === "0") { + if (two.cmp(0) == 0) { //Used cmp function to compare the value alert("Divide by 0 error"); return "0"; } else {