Building a Stylish React Calculator: A Step-by-Step Guide


Introduction


Creating a calculator in React is an excellent way to practice component-based architecture and state management. In this guide, we’ll build a sleek and functional calculator using React.js, covering its structure, components, styling, and additional improvements.


A calculator is a simple yet powerful project to practice:

  • State management using useState
  • Component reusability with modular design
  • Event handling for user interactions
  • Styling techniques to create an attractive UI


By the end of this tutorial, you’ll have a fully functional and stylish calculator built with React.


Project Structure
Our calculator is designed with modular React components, following this directory structure:

/src

  |– components/

        |– calculator/

              |– Display.jsx

              |– ButtonContainer.jsx

  |– App.jsx

  |– Calculator.module.css

  |– App.css


App Component (App.jsx). –
The App component serves as the main logic hub, handling state and user interactions.

import Display from "./components/calculator/Display";
import ButtonContainer from "./components/calculator/ButtonContainer";
import "./App.css";
import styles from "./Calculator.module.css";
import { useState } from "react";

function App() {
  const [calVal, setCalVal] = useState("");

  const onButtonClick = (buttonText) => {
    if (buttonText === 'C') {
      setCalVal("");
    } else if (buttonText === '=') {
      try {
        const result = eval(calVal);
        setCalVal(result);
      } catch (error) {
        setCalVal("Error");
      }
    } else {
      setCalVal(calVal + buttonText);
    }
  };

  return (
    <center className="calculator-container">
      <br />
      <div className={styles.calculator} id="calculator">
        <Display displayValue={calVal} />
        <ButtonContainer onButtonClick={onButtonClick} />
      </div>
    </center>
  );
}
export default App;


Understanding the App Component

  • State Management: useState stores and updates the calculator’s display value.
  • Event Handling: onButtonClick function updates the state based on user input.
  • Error Handling: If an invalid operation is entered, it returns “Error” instead of breaking the application.
  • Component Structure: The Display and ButtonContainer components ensure a clean and modular approach.

Display Component (Display.jsx)
The Display component presents the calculator’s current value stylishly.

import styles from "../../Calculator.module.css";

const Display = ({ displayValue }) => {
  return <input type="text" className={styles.display} value={displayValue} readOnly />;
};
export default Display;


Read-only Input Field: Prevents manual edits and updates dynamically.


Button Container Component (ButtonContainer.jsx)
The ButtonContainer component generates calculator buttons with an intuitive layout.

import styles from "../../Calculator.module.css";

const ButtonContainer = ({ onButtonClick }) => {
  const buttonNames = ['C', '1', '2', '+', '3', '4', '-', '5', '6', '*', '7', '8', '/', '=', '9', '0', '.'];

  return (
    <div className={styles.buttonsContainer}>
      {buttonNames.map((buttonName, index) => (
        <button key={index} className={styles.button} onClick={() => onButtonClick(buttonName)}>
          {buttonName}
        </button>
      ))}
    </div>
  );
};
export default ButtonContainer;


Dynamic Button Generation: Uses map to create buttons dynamically.
Event Binding: Each button triggers the onButtonClick function.


Styling with CSS (Calculator.module.css)
We enhance the calculator’s appearance with modern, responsive styling:

.calculator {
  width: 280px;
  background: linear-gradient(135deg, #333, #444);
  padding: 20px;
  border-radius: 15px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
}
.display {
  width: 100%;
  height: 60px;
  font-size: 1.8rem;
  text-align: right;
  padding: 10px;
  border: none;
  border-radius: 8px;
  background: #000;
  color: #0f0;
}
.buttonsContainer {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
  margin-top: 15px;
}
.button {
  width: 100%;
  height: 55px;
  font-size: 1.4rem;
  font-weight: bold;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease-in-out;
  background: #555;
  color: white;
}
.button:hover {
  background: #777;
}
.button:active {
  transform: scale(0.95);
}
  • Dark Theme: A sleek gradient background for a modern look.
  • Hover Effects: Provides interactive feedback when users click buttons.
  • Grid Layout: Ensures a structured button arrangement.

Possible Enhancements

You can further improve the calculator by adding:

  • Keyboard Support: Allowing users to input values using the keyboard.
  • Scientific Functions: Adding square root, logarithms, and exponentiation.
  • Themes & Animations: Implementing light/dark mode and smooth transitions.


This modern calculator demonstrates how React components, state management, and styling create a seamless user experience. Expand upon it by adding themes, advanced operations, or animations! Happy coding!

Techinfo Avatar

Leave a Reply

Your email address will not be published. Required fields are marked *