21 - Simple Calculator with Basic Operations

Description

Develop a React app for a simple calculator with the following functionalities:

  • Displays a running total and current input.

  • Accepts user input through buttons or keyboard presses for numbers and operators (+, -, *, /).

  • Performs basic arithmetic operations based on chosen operators.

  • Shows the final result after an equals button is clicked.

Algorithm

  1. State Management:

    • Define React state variables to hold:

      • currentNumber: Current user input.

      • total: Running total value.

      • operator: Chosen operator (+, -, *, /).

  2. User Interaction:

    • Handle button clicks or keyboard presses to update currentNumber.

    • Implement button click handlers for operators that update operator.

  3. Calculation Logic:

    • Create functions for each operation that take total and currentNumber as input and return the new total.

    • Perform the chosen operation on total and currentNumber when the equals button is clicked.

  4. Display and Output:

    • Render the currentNumber in the input field.

    • Display the total and chosen operator (if any) above the input field.

    • Show the final result after calculation on a separate display.

Code

import React, { useState } from 'react';

function SimpleCalculator() {
  const [currentNumber, setCurrentNumber] = useState('');
  const [total, setTotal] = useState(0);
  const [operator, setOperator] = useState('');

  const handleNumberClick = (number) => {
    setCurrentNumber(currentNumber + number);
  };

  const handleOperatorClick = (op) => {
    setOperator(op);
    setTotal(currentNumber ? Number(currentNumber) : 0);
    setCurrentNumber('');
  };

  const handleEqualsClick = () => {
    if (operator && currentNumber) {
      let newTotal;
      switch (operator) {
        case '+':
          newTotal = total + Number(currentNumber);
          break;
        case '-':
          newTotal = total - Number(currentNumber);
          break;
        case '*':
          newTotal = total * Number(currentNumber);
          break;
        case '/':
          newTotal = total / Number(currentNumber);
          break;
      }
      setTotal(newTotal);
      setCurrentNumber('');
      setOperator('');
    }
  };

  return (
    <div className="calculator">
      <div className="display">
        {total !== 0 && `${total} ${operator}`}
      </div>
      <input type="text" value={currentNumber} readOnly />
      <div className="buttons">
        <button onClick={() => handleNumberClick('7')}>7</button>
        {/* Other number buttons */}
        <button onClick={() => handleOperatorClick('+')}>+</button>
        {/* Other operator buttons */}
        <button onClick={handleEqualsClick}>=</button>
      </div>
    </div>
  );
}

export default SimpleCalculator;

Explanation

  • State variables hold current number, total, and chosen operator.

  • Button click handlers update state based on user input.

  • Calculator functions perform operations and update total.

  • The UI displays running total, operator, current input, and result.

Additional Notes

  • Consider adding decimal point support using string manipulation or specialized libraries.

  • Implement keyboard shortcuts for numbers and operators.

  • Design a sleek and user-friendly interface with clear buttons and displays.

Last updated