Home Web Front-end JS Tutorial Building a Simple Calculator with React

Building a Simple Calculator with React

Sep 04, 2024 am 07:03 AM

Building a Simple Calculator with React

Introduction

In this tutorial, we'll walk you through building a simple and functional calculator using React. This project is an excellent starting point for beginners looking to get hands-on experience with React and understand how to manage state and handle events in a React application.

Project Overview

This calculator project allows users to perform basic arithmetic operations like addition, subtraction, multiplication, and division. The calculator has a sleek, user-friendly interface, and it handles all the essential operations, including clearing the input, deleting the last entered value, and calculating the result.

Features

  • Basic Arithmetic Operations: Supports addition, subtraction, multiplication, and division.
  • Clear (AC) and Delete (DEL) Functionality: Easily clear all inputs or delete the last entered digit.
  • Responsive Design: Works well on various screen sizes, with an intuitive button layout.
  • Error Handling: Displays an error message if an invalid operation is performed.

Technologies Used

  • React: For building the user interface.
  • CSS: For styling the application and ensuring a responsive design.

Project Structure

The project is structured as follows:

├── public
├── src
│   ├── components
│   │   └── Calculator.jsx
│   ├── App.jsx
│   ├── App.css
│   ├── index.js
│   └── index.css
├── package.json
└── README.md
Copy after login

Key Components

  • Calculator.jsx: Contains the main logic for the calculator, including state management and event handling.
  • App.jsx: Wraps the Calculator component and handles the overall layout of the application.
  • App.css: Contains the styling for the Calculator component.

Code Explanation

Calculator Component

The Calculator component manages the state of the calculator's input and result using the useState hook. It includes a handleClick function that handles button clicks and updates the state accordingly. The calculateResult function evaluates the input using JavaScript's eval function and updates the result.

import  { useState } from "react";

const Calculator = () => {
  const [input, setInput] = useState("");
  const [result, setResult] = useState("");

  const handleClick = (value) => {
    if (value === "AC") {
      setInput("");
      setResult("");
    } else if (value === "DEL") {
      setInput(input.slice(0, -1));
    } else if (value === "=") {
        setResult("")
      calculateResult();
    } else {
      setInput(input + value);
    }
  };

  const calculateResult = () => {
    try {
      setInput(eval(input));
    } catch (error) {
      setResult("Enter Valid Operation");
    }
  };

  return (
    <div className="calculator">
      <div className="output-box">
        <h1>{input}</h1>
        <h2>{result}</h2>
      </div>
      <div className="buttons">
        <div className="row-1">
          <button onClick={() => handleClick("AC")}>
            <p>AC</p>
          </button>
          <button onClick={() => handleClick("DEL")}>
            <p>DEL</p>
          </button>
          <button onClick={() => handleClick("%")}>
            <p>%</p>
          </button>
          <button onClick={() => handleClick("/")}>
            <p>÷</p>
          </button>
        </div>
        <div className="row-2">
          <button onClick={() => handleClick("7")}>
            <p>7</p>
          </button>
          <button onClick={() => handleClick("8")}>
            <p>8</p>
          </button>
          <button onClick={() => handleClick("9")}>
            <p>9</p>
          </button>
          <button onClick={() => handleClick("*")}>
            <p>X</p>
          </button>
        </div>
        <div className="row-3">
          <button onClick={() => handleClick("4")}>
            <p>4</p>
          </button>
          <button onClick={() => handleClick("5")}>
            <p>5</p>
          </button>
          <button onClick={() => handleClick("6")}>
            <p>6</p>
          </button>
          <button onClick={() => handleClick("-")}>
            <p>-</p>
          </button>
        </div>
        <div className="row-4">
          <button onClick={() => handleClick("1")}>
            <p>1</p>
          </button>
          <button onClick={() => handleClick("2")}>
            <p>2</p>
          </button>
          <button onClick={() => handleClick("3")}>
            <p>3</p>
          </button>
          <button onClick={() => handleClick("+")}>
            <p>+</p>
          </button>
        </div>
        <div className="row-5">
          <button id="zero-button" onClick={() => handleClick("0")}>
            <p>0</p>
          </button>
          <button onClick={() => handleClick(".")}>
            <p>.</p>
          </button>
          <button onClick={() => handleClick("=")}>
            <p>=</p>
          </button>
        </div>
      </div>
    </div>
  );
};

export default Calculator;

Copy after login

App Component

The App component renders the Calculator component and adds a header and footer to the application.

import Calculator from "./components/Calculator";
import "./App.css";
const App = () => {
  return (
    <div className="app">
      <div className="header">
        <h1>Calculator</h1>
      </div>
      <Calculator />
      <div className="footer">
        <p>Made with ❤️ by Coding4Dev</p>
      </div>
    </div>
  );
};

export default App;

Copy after login

CSS Styling

The CSS styles ensure the calculator is centered on the screen and has a modern look. Buttons are styled for a clean and responsive design.

* {
  box-sizing: border-box;
}
body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
}
.app {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.header {
  margin: 20px;
}

.calculator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 350px;
  height: 450px;
  color: white;
  background-color: black;
  border-radius: 15px;
  box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
}
.output-box {
  width: 300px;
  height: 100px;
  color: rgb(53, 52, 52);
  background-color: rgb(216, 216, 216);
  border-radius: 12px;
}
.output-box h1 {
  margin-left: 15px;
  font-size: 25px;
  overflow: hidden;
}
.output-box h2 {
  margin-left: 15px;
  font-size: 25px;
}
.buttons {
  margin-top: 15px;
  width: 350px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.buttons p {
  font-size: 14px;
  font-weight: 600;
  color: white;
}
button {
  width: 72px;
  margin: 4px;
  border-radius: 12px;
  border: none;
  background-color: #536493;
}
button:hover {
  background-color: #374262;
}
#zero-button {
  width: 150px;
}
.footer {
  margin: 20px;
}

Copy after login

Installation and Usage

To get started with this project, clone the repository and install the dependencies:

git clone https://github.com/abhishekgurjar-in/Calculator.git
cd calculator-react
npm install
npm start
Copy after login

This will start the development server and open the calculator in your default web browser.

Live Demo

You can check out the live demo of the calculator here.

Conclusion

This simple calculator project is an excellent way to practice your React skills and understand how to manage state and handle user input in a React application. Feel free to expand this project by adding more advanced features like a scientific calculator mode or integrating additional functionality.

Credits

  • Inspiration: This project was inspired by various Simple calculators available online.

Author

Abhishek Gurjar is a passionate web developer with a focus on building intuitive and responsive web applications. Follow his journey and explore more projects on GitHub.

The above is the detailed content of Building a Simple Calculator with React. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles