I´m trying to simplify my code. Currently, lots of “if” statement which I want to turn into a switch case. The biggest one seems to be the operations one. I thought about setting up a classname in the operations buttons and using that in the else if. Unfortunately, setting up a variable (eg, operations=document.getElementByClassName(“operations”) doesn´t work since it doesn´t return an individual item, rather a NodeList. Using “indexOf” didn´t work either. Any ideas?
class Calculator extends Component {
constructor(props) {
super(props);
this.state = {value:0,decimal: false}
this.handleClick = this.handleClick.bind(this);
}
handleClick(evt) {
const id = evt.target.id;
const result = evt.target.value;
if (id === "clear") {
this.setState({ value: 0, decimal: false });
}
else if (id === "equals") {
const res = math.eval(this.state.value);
this.setState(prevState => ({
value: res,
decimal: false
}));
}
else if (id === "decimal") {
this.setState({ decimal: true });
if (!this.state.decimal) {
this.setState(prevState => ({
value: prevState.value + result
}));
}
}
else {
if (
id === "add" ||
id === "subtract" ||
id === "multiply" ||
id === "divide"
) {
this.setState({
decimal: false
});
}
this.setState(prevState => ({
value: `${prevState.value}${result}`
.replace(/([/+\-/*=])([/+\-*=])/g, "$2")
.replace(/^0+(?=[1-9])/, "")
.replace(/^0+(?=\.)/, "0")
.replace(/^0+\B/, "")
}));
}
}
render() {
return(
<div id="container">
<Display value={this.state.value} />
<div>
<Button onClick={this.handleClick} id="one" value={'1'} />
<Button onClick={this.handleClick} id="two" value={'2'}/>
<Button onClick={this.handleClick} id="three" value={'3'} />
<Button onClick={this.handleClick} id="divide" value={'/'} />
</div>
<div>
<Button onClick={this.handleClick} id="four" value={'4'} />
<Button onClick={this.handleClick} id="five" value={'5'} />
<Button onClick={this.handleClick} id="six" value={'6'} />
<Button onClick={this.handleClick} id="add" value={'+'} />
</div>
<div>
<Button onClick={this.handleClick} id="seven" value={'7'} />
<Button onClick={this.handleClick} id="eight" value={'8'} />
<Button onClick={this.handleClick} id="nine" value={'9'} />
<Button onClick={this.handleClick} id="subtract" value={'-'} />
</div>
<div>
<Button onClick={this.handleClick} id="zero" value={'0'} />
<Button onClick={this.handleClick} id="decimal" value={'.'} />
<Button onClick={this.handleClick} id="equals" value={'='} />
<Button onClick={this.handleClick} id="multiply" value={'*'} />
</div>
<div>
<Button onClick={this.handleClick} id="clear" value={'clear'} />
</div>
</div>
)
}
I tried this, but didn´t work:
handleClick(evt,id) { const id = evt.target.id; const result = evt.target.value; switch(id){ case"clear": this.setState({ value: 0, decimal: false }); break; (all operations) default: this.setState(prevState => ({ value: `${prevState.value}${result}` .replace(/([/+\-/*=])([/+\-*=])/g, "$2") .replace(/^0+(?=[1-9])/, "") .replace(/^0+(?=\.)/, "0") .replace(/^0+\B/, "") })) }