I have a calculator (in React) and I wonder if the way I did is is good or what I could improve. I wanted to do it like the iphone calculator (you dont only see results when you press =) and I feel like my code became a little messy. Any suggestions would be awesome! Ps. I didn't yet add more then +,-,/.*,= operations.
I also added the code on codepen:
https://codepen.io/julianyc/pen/bXwxbg?editors=1010
const math_it_up = {
['+']: function (x, y) {
console.log(x, y, typeof x, typeof y, "blaaa")
return x + y
},
['-']: function (x, y) {
return x - y
},
['*']: function (x, y) {
console.log(x, y, typeof x, typeof y, "blaaa")
return x * y
},
['/']: function (x, y) {
return x / y
}
}
class App extends React.Component {
state = {
result: 0,
operator: "",
currentNum: "",
show: 0
};
onClick = (elem) => {
if (isNaN(elem)) {
if (elem === "=") {
this.setState({
showResult: this.state.result
})
} else {
this.setState({
operator: elem,
show: this.state.result ? this.state.result : null
})
}
}
else {
if (!this.state.currentNum) {
this.setState({
currentNum: parseInt(elem),
result: parseInt(elem),
show: elem
})
} else {
if (this.state.operator) {
this.setState({
currentNum: parseInt(elem),
result: math_it_up[this.state.operator](this.state.result, parseInt(elem)),
show: elem
})
}
}
}
};
render() {
return (
<div>
<Key onClick={this.onClick}/>
<h1>{this.state.show}</h1>
</div>
)
}
}
const Key = ({onClick}) => {
const renderNumbers = () => {
const arr = [0,1,2,3,4,5,6,7,8,9];
return arr.map((val, i) => {
return <button key={i} name={val} onClick={(e) => onClick(e.target.name)}>{val}</button>
})
};
const renderCalculationKeys = () => {
const arr = ["+", "-", "/", "*", "="];
return arr.map((val, i) => {
return <button key={i} name={val} onClick={(e) => onClick(e.target.name)}>{val}</button>
})
};
return (
<div>
{renderNumbers()}
{renderCalculationKeys()}
</div>
)
};
ReactDOM.render(
<App />,
document.getElementById('root')
);