Community for developers to learn, share their programming knowledge. Register!
Create First React Project

Creating a Simple Calculator with React


In this guide, you’ll get hands-on training on how to create a simple yet functional calculator using React. Whether you're expanding your React knowledge or stepping into the world of frontend development, this project is perfect for honing your skills. We’ll cover everything from setting up the environment to deploying your application. By the end, you’ll have a fully functional calculator and a deeper understanding of React concepts like components, state, and event handling.

Let’s get started!

Setting Up the React Development Environment

Before diving into the project, ensure that your development environment is ready. The first step is to install Node.js and npm (Node Package Manager), as React relies on these tools. You can download them from the official Node.js website. Once installed, verify the installation by running the following commands in your terminal:

node -v
npm -v

Next, use the create-react-app CLI tool to scaffold your React project. Open your terminal and run:

npx create-react-app calculator-app

This command will generate the necessary files and dependencies for a React project. Navigate to the project folder and start the development server:

cd calculator-app
npm start

Your browser should open a page displaying the default React app. Congratulations! Your environment is ready.

Creating the Basic React App Structure

With the environment set up, let’s clean up the boilerplate code. Inside the src folder, delete unnecessary files like logo.svg and unused CSS files. Replace the contents of App.js with a simple component structure:

import React from 'react';

function App() {
  return (
    <div className="App">
      <h1>React Calculator</h1>
    </div>
  );
}

export default App;

This structure provides a clean slate to build the calculator.

Designing the Calculator Layout

A calculator has a simple layout: a display screen and a grid of buttons for numbers and operations. Use JSX to design the layout in the App.js file. Here’s an example:

function App() {
  return (
    <div className="calculator">
      <div className="display">0</div>
      <div className="buttons">
        <button>7</button>
        <button>8</button>
        <button>9</button>
        <button>/</button>
        <button>4</button>
        <button>5</button>
        <button>6</button>
        <button>*</button>
        <button>1</button>
        <button>2</button>
        <button>3</button>
        <button>-</button>
        <button>0</button>
        <button>=</button>
        <button>+</button>
        <button>C</button>
      </div>
    </div>
  );
}

At this stage, the layout is purely presentational.

Building Calculator Components

To make the code modular, split the application into smaller components. Create separate components for the Display and ButtonPanel. For example:

Display.js

import React from 'react';

const Display = ({ value }) => {
  return <div className="display">{value}</div>;
};

export default Display;

ButtonPanel.js

import React from 'react';

const ButtonPanel = ({ onClick }) => {
  const buttons = ['7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '=', '+', 'C'];
  return (
    <div className="buttons">
      {buttons.map((button) => (
        <button key={button} onClick={() => onClick(button)}>
          {button}
        </button>
      ))}
    </div>
  );
};

export default ButtonPanel;

Managing State for Calculator Operations

React’s useState hook will manage the calculator’s state. Add state in the App.js to track the current input and result:

import React, { useState } from 'react';
import Display from './Display';
import ButtonPanel from './ButtonPanel';

function App() {
  const [input, setInput] = useState('0');

  const handleButtonClick = (buttonValue) => {
    // Logic for button click will go here
  };

  return (
    <div className="calculator">
      <Display value={input} />
      <ButtonPanel onClick={handleButtonClick} />
    </div>
  );
}

export default App;

Implementing Button Click Handlers

The button click handler determines what happens when a user clicks a button. For instance:

const handleButtonClick = (buttonValue) => {
  if (buttonValue === 'C') {
    setInput('0');
  } else if (buttonValue === '=') {
    try {
      setInput(eval(input).toString()); // Caution: Avoid eval in production
    } catch {
      setInput('Error');
    }
  } else {
    setInput(input === '0' ? buttonValue : input + buttonValue);
  }
};

Performing Calculations and Displaying Results

The eval() function (used above) evaluates the string input as a mathematical expression. For better security, consider using a math library like math.js for handling calculations.

Adding Clear Functionality

The clear (C) button resets the state:

if (buttonValue === 'C') {
  setInput('0');
}

This ensures a fresh start for new calculations.

Styling the Calculator for Better User Experience

Use CSS to make the calculator visually appealing. Add the following styles to App.css:

.calculator {
  width: 300px;
  margin: 50px auto;
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
}

.display {
  font-size: 2em;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.buttons button {
  width: 60px;
  height: 60px;
  margin: 5px;
  font-size: 1.2em;
}

Testing the Calculator Functionality

Test your calculator by performing different operations: addition, subtraction, multiplication, and division. Edge cases, such as dividing by zero or entering invalid sequences, should also be tested.

Deploying Calculator Application

Once satisfied, deploy your application. Use a platform like Netlify or Vercel to host your calculator. Build the app for production with:

npm run build

Then follow the chosen platform's deployment instructions.

Summary

Creating a simple calculator with React is an excellent way to strengthen your understanding of React fundamentals. You’ve learned how to set up the environment, create components, manage state, handle user interactions, and deploy your application. By completing this project, you’ve taken a significant step in mastering React development. Keep experimenting and building—your learning journey has just begun!

Last Update: 24 Jan, 2025

Topics:
React