Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Create an Age Calculator App using React-Native
Next article icon

ReactJS Calculator App (Adding Functionality)

Last Updated : 28 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We are going to build a project. that is a basic calculator application in ReactJS. It takes input from button clicks, builds a mathematical expression, and displays the result. The app includes functionalities like clearing the screen, deleting the last input, and handling errors.

Preview Image

Output_preview

Prerequisite

  • NPM
  • ReactJS

Approach

  • The UI will consist of a display screen and several buttons for digits, operations, clear, delete, and equals.
  • The question holds the ongoing mathematical expression, and the answer holds the result.
  • Each button triggers a handleClick function, updating the state based on the button’s function (e.g., digit, operator, clear, or equals).
  • Error states like division by zero or invalid expressions are managed by try-catch blocks, displaying “Math Error” when necessary.

Steps to Create Calculator React Application

Step 1: Initialize the React Application

npm create vite@latest calculator-app --template react 

Select the following options:

terminal

Termoinal

Step 2: Navigate to the React App

cd calculator-app

Step 3: Install all the dependencies

npm install

Project Structure:

project_structure

Project Structure

Updated Dependencies:

 },
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1"
},

Example: This example shows the creation of calculator.

CSS
/* App.css */ body {     font-family: Arial, sans-serif;     background-color: #f0f0f0;     display: flex;     justify-content: center;     align-items: center;     height: 100vh; }  .calculator {     width: 320px;     background-color: white;     border-radius: 10px;     box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);     padding: 20px; }  h2 {     text-align: center;     margin-bottom: 20px; }  .screen {     display: flex;     flex-direction: column;     margin-bottom: 15px; }  .screen input {     height: 40px;     font-size: 1.5em;     padding: 5px;     border: 1px solid #ddd;     border-radius: 5px;     margin-bottom: 5px;     text-align: right; }  .button-row {     display: grid;     grid-template-columns: repeat(4, 1fr);     gap: 10px; }  button {     padding: 15px;     font-size: 1.2em;     background-color: #e0e0e0;     border: none;     border-radius: 5px;     cursor: pointer;     transition: background-color 0.2s ease; }  button:hover {     background-color: #d5d5d5; }  button:active {     background-color: #c0c0c0; }  /* Styles for the equals button */ .equals {     background-color: #4caf50;     /* Green background */     color: white;     /* White text */ }  .equals:hover {     background-color: #45a049;     /* Darker green on hover */ }  /* Styles for the clear button */ .clear {     background-color: #ff5722;     /* Red background */     color: white;     /* White text */ }  .clear:hover {     background-color: #e64a19;     /* Darker red on hover */ } 
JavaScript
// App.jsx  import React, { useState } from 'react'; import './App.css';  const Calculator = () => {   const [input, setInput] = useState('');   const [result, setResult] = useState('');    const handleClick = (value) => {     if (value === '=') {       try {         const evalResult = eval(input);         setResult(evalResult);         setInput('');       } catch (error) {         setResult('Math Error');         setInput('');       }     } else if (value === 'Clear') {       setInput('');       setResult('');     } else {       setInput((prev) => prev + value);     }   };    return (     <div className="calculator">       <h2>React Calculator</h2>       <div className="screen">         <input type="text" readOnly value={input} placeholder="0" />         <input type="text" readOnly value={result} placeholder="Result" />       </div>       <div className="button-row">         {['7', '8', '9', '/'].map((item) => (           <button key={item} onClick={() => handleClick(item)}>             {item}           </button>         ))}         {['4', '5', '6', '*'].map((item) => (           <button key={item} onClick={() => handleClick(item)}>             {item}           </button>         ))}         {['1', '2', '3', '-'].map((item) => (           <button key={item} onClick={() => handleClick(item)}>             {item}           </button>         ))}         <button onClick={() => handleClick('0')}>0</button>         <button onClick={() => handleClick('+')}>+</button>         <button className="equals" onClick={() => handleClick('=')}>=</button>         <button className="clear" onClick={() => handleClick('Clear')}>Clear</button>       </div>     </div>   ); };  export default Calculator; 

Output:



Next Article
Create an Age Calculator App using React-Native
author
harsh.agarwal0
Improve
Article Tags :
  • Project
  • ReactJS
  • Web Technologies
  • ReactJS-Projects
  • Web Development Projects

Similar Reads

  • ReactJS | Calculator App ( Introduction )
    We have seen so far what React is and what it is capable of. To summarise in brief we got to know what React web apps are, React Components, Props, States, and the lifecycle of a React component. We also created a basic clock application using all of the following. But React is a javascript library
    3 min read
  • Create an Age Calculator App using React-Native
    In this article we are going to implement a Age calculator using React Native. An age calculator app in React Native is a simple application that calculates a person's age based on their birth date and the current date. It's a simple utility designed to determine how many years, months, and days hav
    3 min read
  • Create a BMI Calculator App using React-Native
    In this article, we will create a BMI (Body Mass Index) calculator using React Native. A BMI calculator serves as a valuable and straightforward tool for estimating body fat by considering height and weight measurements.A BMI Calculator App built with React Native allows users to input their age, he
    4 min read
  • ReactJS Calculator App (Building UI)
    We created our first app and deleted all those files we did not need, and created some of the files that we will need in the future. Now as we stand in our current situation we have a blank canvas before us where we will have to create our calculator app. We will be creating the project in multiple
    4 min read
  • Calculator App Using Angular
    This Calculator app will provide basic arithmetic functionalities such as addition, subtraction, multiplication, and division, with a clean and modern UI. It will be fully responsive and interactive, ensuring a great user experience across different devices. This project is suitable for both beginne
    4 min read
  • Aspect Ratio Calculator using React
    In this React project, we'll build an interactive Aspect Ratio Calculator where users can upload images to visualize aspect ratios and adjust width and height values for live previews. Preview of final output: Let us have a look at how the final output will look like. PrerequisitesReactCSSJSXFunctio
    4 min read
  • Build a Calculator using React Native
    React Native is a well-known technology for developing mobile apps that can run across many platforms. It enables the creation of native mobile apps for iOS and Android from a single codebase. React Native makes it simple to construct vibrant, engaging, and high-performing mobile apps. In this tutor
    6 min read
  • Create a Calculator App Using Next JS
    Creating a Calculator app is one of the basic projects that clears the core concept of a technology. In this tutorial, we'll walk you through the process of building a calculator app using Next.js. Output Preview: Let us have a look at how the final output will look like. Prerequisites:NPM & Nod
    3 min read
  • ReactJS Calculator App (Styling)
    Now that we have added functionality to our Calculator app and successfully created a fully functional calculator application using React. But that does not look good despite being fully functional. This is because of the lack of CSS in the code. Let's add CSS to our app to make it look more attract
    3 min read
  • How to create a Dictionary App in ReactJS ?
    In this article, we will be building a very simple Dictionary app with the help of an API. This is a perfect project for beginners as it will teach you how to fetch information from an API and display it and some basics of how React actually works. Also, we will learn about how to use React icons. L
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences