0

I cannot get why I get an error message (the default case) even I if I clicked on + - ÷ * ?? is not it supposed to set the state like i defined in the switch case ?I thought it would set the state

here is my code please tell me what I did wrong??

class App extends React.Component { constructor(props){ super(props); this.state={ num:[], sign:"", res:0 } this.handleclick=this.handleclick.bind(this); this.handelAssign=this.handelAssign.bind(this); } handleclick(ele) { this.setState({ num: [...this.state.num, ele] }); this.handelAssign(ele); }; handelAssign = (operator) => { /**operatior could be + - * ÷ */ switch (operator) { case operator === "+": this.setState({ operator: "+" }); break; case operator === "-": this.setState({ operator: "-" }); break; case operator === '*': this.setState({ operator: "*" }); break; case operator === "÷": this.setState({ operator: "/" }); break; default: throw new Error('sorry you must enter a valid operator') }}; render() { const buttons = ["÷", 1, 2, 3, "*", 4, 5, 6,"+", 7, 8, 9, ".", 0, "-"]; let allbuttons=""; return ( <div className="calculation-grid"> <div className="output"> <div className="previous-operand">{this.state.num}</div> <div className="current-operand"></div> </div> <button className="span-two">AC</button> <button>DEL</button> {allbuttons=buttons.map((ele)=><button onClick={()=>this.handleclick(ele) } key={ele}>{ele}</button>)} <button className="span-two">=</button> </div> ); } } 

2 Answers 2

1

Could you try with this :

 handelAssign = (operator) => { /**operatior could be + - * ÷ */ switch (operator) { case "+": this.setState({ operator: "+" }); break; case "-": this.setState({ operator: "-" }); break; case '*': this.setState({ operator: "*" }); break; case "÷": this.setState({ operator: "/" }); break; default: throw new Error('sorry you must enter a valid operator') }}; 
Sign up to request clarification or add additional context in comments.

Comments

0

Try removing the condition from swtich case

handelAssign = (operator) => { /**operatior could be + - * ÷ */ switch (operator) { case "+": this.setState({ operator: "+" }); break; case "-": this.setState({ operator: "-" }); break; case "*": this.setState({ operator: "*" }); break; case "÷": this.setState({ operator: "/" }); break; default: throw new Error('sorry you must enter a valid operator') }}; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.