How To Build a Calculator Using React JS

Udemezue John - Oct 10 - - Dev Community

How Do I Build a Calculator Using React JS?

Creating a calculator in React JS is an engaging project that can help solidify your understanding of the framework and its core concepts. This guide will take you through the steps of building a simple yet functional calculator.

I’ll walk you through the entire process, from setting up your development environment to implementing the calculator’s functionalities. Let’s get started!

Prerequisites

Before diving into the project, ensure you have the following:

  • Basic understanding of JavaScript: Familiarity with JavaScript syntax, functions, and arrays will be essential.
  • Node.js installed: This is necessary for setting up React. You can download it from Node.js Official Website.
  • Basic knowledge of React: Understanding components, state, and props will be helpful but not mandatory.

1. Setting Up the Project

Create a New React App

Open your terminal and run the following command to create a new React app using Create React App:

npx create-react-app calculator-app
cd calculator-app

Enter fullscreen mode Exit fullscreen mode

This will set up a new React project in a folder called calculator-app.

2.Start the Development Server

To see your app in action, start the development server:

npm start

Enter fullscreen mode Exit fullscreen mode

Your default browser should open at http://localhost:3000, displaying the default React app.

Building the Calculator

3. Structure the Components

A calculator typically consists of a display and buttons for digits and operations. I’ll create two main components: Calculator and Button.

Create a new folder called components inside the src directory.
Inside components, create two files: Calculator.js and Button.js.
Implement the Button Component

The Button component will represent each button on the calculator. Here’s a simple implementation:

// src/components/Button.js
import React from 'react';

const Button = ({ label, onClick }) => {
  return (
    <button className="button" onClick={() => onClick(label)}>
      {label}
    </button>
  );
};

export default Button;
Enter fullscreen mode Exit fullscreen mode

4. Implement the Calculator Component

Now, let’s implement the Calculator component. This component will manage the calculator’s state and render the buttons and display.

// src/components/Calculator.js
import React, { useState } from 'react';
import Button from './Button';
import './Calculator.css'; // Optional CSS file for styling

const Calculator = () => {
  const [input, setInput] = useState('');

  const handleButtonClick = (label) => {
    if (label === '=') {
      try {
        setInput(eval(input)); // Caution: Using eval() can be dangerous
      } catch {
        setInput('Error');
      }
    } else if (label === 'C') {
      setInput('');
    } else {
      setInput(input + label);
    }
  };

  const buttons = [
    '7', '8', '9', '/',
    '4', '5', '6', '*',
    '1', '2', '3', '-',
    'C', '0', '=', '+'
  ];

  return (
    <div className="calculator">
      <div className="display">{input}</div>
      <div className="buttons">
        {buttons.map((label) => (
          <Button key={label} label={label} onClick={handleButtonClick} />
        ))}
      </div>
    </div>
  );
};

export default Calculator;
Enter fullscreen mode Exit fullscreen mode

5. Styling the Calculator

You can add some basic CSS styles to make the calculator visually appealing. Create a CSS file named Calculator.css in the components folder:

/* src/components/Calculator.css */
.calculator {
  width: 320px;
  margin: 50px auto;
  border: 1px solid #ccc;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.display {
  background-color: #222;
  color: white;
  font-size: 2rem;
  padding: 20px;
  text-align: right;
}

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

.button {
  padding: 20px;
  font-size: 1.5rem;
  border: none;
  background-color: #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.button:hover {
  background-color: #ddd;
}
Enter fullscreen mode Exit fullscreen mode

6. Using the Calculator Component

Finally, integrate the Calculator component into your main application. Modify src/App.js as follows:

// src/App.js
import React from 'react';
import Calculator from './components/Calculator';

const App = () => {
  return (
    <div>
      <h1>Simple Calculator</h1>
      <Calculator />
    </div>
  );
};

export default App;

Enter fullscreen mode Exit fullscreen mode

Final Touches

7. Test the Application

Once you have everything set up, go back to your browser. You should see a simple calculator interface that can perform basic arithmetic operations.

Considerations and Improvements.

  • Security: Using eval() poses a security risk. Consider implementing a safer parsing method for arithmetic expressions.
  • Feature Expansion: You can enhance the calculator by adding more functionalities, such as decimal support, keyboard input, or scientific functions. Responsive Design: Use media queries in your CSS to ensure that your calculator looks good on different screen sizes.

Conclusion.

Building a calculator in React JS is a great way to practice your skills and understand how components work together in a real-world application.

This project not only reinforces your knowledge of React but also introduces you to the concepts of state management and event handling.

As you advance, consider implementing more complex features to challenge yourself and deepen your understanding.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player