Home > Software design >  why is the switch function not working in reactjs?
why is the switch function not working in reactjs?

Time:03-07

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>
    );
  }
}

CodePudding user response:

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')
    }};

CodePudding user response:

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')
    }};
  • Related