skip to Main Content
const Calculatorpage = () => {

    function calculate() {
        const firstNum = Number(document.getElementById('firstNum').value)
        const secondNum = Number(document.getElementById('secondNum').value)
        const symbol = document.getElementById('symbol').value
        const result = document.getElementById('result')
        console.log("im in");
        let res
        switch (symbol) {
            case "+": res = secondNumber + firstNumber
                
                break;
        
            default:
                break;
        }
       
        result.value = res

    }

    return (
        <div>
            <input id="firstNum" type="number" />
            <input id="symbol" placeholder="+" type="symbol" />
            <input id="secondNum" type="number" />
            <input id="result" type="number" />
            <button type="submit" onClick={calculate}>Go</button>
        </div>
    )

}

This is how I am using it, but it says that case is a forbidden word?
how can use switch case and what’s the syntax I am supposed to use, I don’t want to use if else constructor?

3

Answers


  1. Please check this , your code is correct just need to cleaned up :

    const Calculate = () => {
      function calculate() {
        const firstNum = Number(document.getElementById("firstNum").value);
        const secondNum = Number(document.getElementById("secondNum").value);
        const symbol = document.getElementById("symbol").value;
        const result = document.getElementById("result");
        console.log("im in");
        let res = 0;
        switch (symbol) {
          case "+":
            res = secondNum + firstNum;
            break;
          default:
            break;
        }
        result.value = res;
      }
    
      return (
        <div>
          <input id="firstNum" type="number" />
          <input id="symbol" placeholder="+" type="symbol" />
          <input id="secondNum" type="number" />
          <input id="result" type="number" />
          <button type="submit" onClick={calculate}>
            Go
          </button>
        </div>
      );
    };
    
    export default Calculate;
    

    first letter of component name must be a uppercase letter

    demo on codesandbox

    Login or Signup to reply.
  2. Can you attempt this which I think is a way cleaner too: Get that switch out of the render in a function and just call it passing the params you want

    Login or Signup to reply.
  3. Using native DOM methods with React is not "the React Way". It will cause conflicts as React has its own way of reconciling changes to the DOM through state manipulation.

    So here’s an example that uses state.

    const { useState } = React;
    
    function Example() {
    
      // Set two states - one for the result initialised to zero
      // and another to hold the states of your input elements - initialised
      // to an object with first, second, and operator properties
      const [ result, setResult ] = useState(0);
      const [ calc, setCalc ] = useState({ first: 0, second: 0, operator: '' });
    
      // When an input changes we take the id and value from
      // it, and update the state with that information
      function handleChange(e) {
        const { id, value } = e.target;
        setCalc(prev => {
          return { ...prev, [id]: value };
        });
      }
      
      // When the button is clicked we calculate the result
      // by operating on the first and second values, and adding
      // the result to the "result" state
      // If you wanted to shortcut the conditions you could
      // alternatively use `eval`:
      // const result = eval(`${calc.first}${calc.operator}${calc.second}`);
      function handleClick() {
        
        const { first, operator, second } = calc;
        
        let result;
        
        if (operator === '+') result = +first + +second;
        if (operator === '-') result = +first - +second;
        if (operator === '*') result = +first * +second;
        if (operator === '/') result = +first / +second;
        
        if (!isNaN(result)) setResult(result);
      
      }
    
      // Each input has a change listener attached to it
      // which calls `handleChange`, and the button has an click
      // listener attached to it which calls `handleClick`.
      // The value of "result" is the result state
      return (
        <div>
          <input
            id="first"
            type="number"
            onChange={handleChange}
          />
          <input
            id="operator"
            placeholder="+"
            type="text"
            onChange={handleChange}
          />
          <input
            id="second"
            type="number"
            onChange={handleChange}
          />
          <input
            id="result"
            type="number"
            value={result}
          />
          <button type="submit" onClick={handleClick}>Go</button>
        </div>
      );
    
    }
    
    ReactDOM.render(
      <Example />,
      document.getElementById('react')
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
    <div id="react"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search