React Calculator App

The React Calculator App is a simple yet important project to learn state management, event handling, and rendering in React. This app allows users to perform basic arithmetic operations and provides an interactive interface with distinct colors for numbers and operators.

React Calculator App Screenshot

Features of the Calculator App

  • Basic arithmetic operations: addition, subtraction, multiplication, and division.
  • Interactive buttons for numbers and operators.
  • Clear button to reset the calculator.
  • Styled interface with distinct colors for numbers and operators.

Explanation of the Program

1. State Management

We use the useState hook to manage the state of the current input and the calculation result:

  • const [input, setInput] = useState('');: Tracks the current input string displayed on the calculator screen.
  • const [result, setResult] = useState('');: Stores the result of the calculation after pressing the equals button.

2. Event Handling

Event handlers are used to update the state when buttons are clicked:

  • handleButtonClick: Appends the clicked button value to the current input.
  • calculateResult: Evaluates the input string using eval and updates the result.
  • clearInput: Resets both the input and result states.

Complete React Calculator Application

Create an empty React Application, and edit the App.js, and App.css files.

The following is the screenshot of project explorer in Visual Studio Code.

Explorer

Project Explorer Screenshot for React Calculator Application

App.js

</>
Copy
import React, { useState } from 'react';
import './App.css';

function CalculatorApp() {
  const [input, setInput] = useState('');
  const [result, setResult] = useState('');

  const handleButtonClick = (value) => {
    setInput(input + value);
  };

  const calculateResult = () => {
    try {
      setResult(eval(input).toString());
    } catch (error) {
      setResult('Error');
    }
  };

  const clearInput = () => {
    setInput('');
    setResult('');
  };

  return (
    <div className="calculator-app">
      <h1>React Calculator</h1>
      <div className="screen">
        <div className="input">{input || '0'}</div>
        <div className="result">{result}</div>
      </div>
      <div className="buttons">
        {["7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"].map((btn) => (
          <button
            key={btn}
            className={btn.match(/[0-9.]/) ? 'number' : 'operator'}
            onClick={() =>
              btn === '='
                ? calculateResult()
                : btn === 'C'
                ? clearInput()
                : handleButtonClick(btn)
            }
          >
            {btn}
          </button>
        ))}
        <button className="clear" onClick={clearInput}>C</button>
      </div>
    </div>
  );
}

export default CalculatorApp;

App.cs

</>
Copy
.calculator-app {
  font-family: Arial, sans-serif;
  margin: 20px auto;
  max-width: 300px;
  text-align: center;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f9f9f9;
}

h1 {
  color: #333;
  margin-bottom: 20px;
}

.screen {
  border: 1px solid #ddd;
  padding: 10px;
  margin-bottom: 20px;
  border-radius: 4px;
  background-color: #fff;
}

.input {
  font-size: 18px;
  color: #333;
  text-align: right;
}

.result {
  font-size: 24px;
  color: #007bff;
  text-align: right;
}

.buttons {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}

button {
  padding: 15px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

button.number {
  background-color: #007bff;
  color: white;
}

button.operator {
  background-color: #28a745;
  color: white;
}

button.clear {
  grid-column: span 4;
  background-color: #dc3545;
  color: white;
}

Conclusion

The React Calculator App demonstrates how to handle state, user input, and dynamic rendering effectively. It serves as a stepping stone for building more complex React applications with advanced functionalities. Experiment with styling and additional features to make it your own!