🧮

Building a Calculator using React: Key Concepts and Steps

Jul 4, 2024

Building a Calculator using React: Key Concepts and Steps

Introduction

  • Goal: Build a calculator using React without relying on a math library.
  • Importance: Introduces key programming concepts essential for becoming a proficient programmer.

Getting Started

  • Initial Setup: Create a blank React application, delete unnecessary files.
  • Layout: Use CSS Grid for layout.
    • Create a div with class calculator-grid.
    • Add a black section for output with divs for previous and current operands.
    • Create buttons for digits, operations, and special functions like AC (All Clear) and Delete.

Styling with CSS

  • Stylesheet: Create styles.css and import it in App.js.
  • Global Styles:
    • Set box-sizing to border-box.
    • Remove margin from body and set a linear gradient background.
  • Grid Layout:
    • Define grid template columns and rows.
    • Implement span-2 class for buttons that span two columns.
  • Output Styles:
    • Apply styles for previous and current operands.
    • Use flexbox for layout within the output section.
  • Button Styles: Set styles for buttons including hover and focus states.
  • Centering: Center the calculator grid on the screen.

Implementing Functionality with Reducer

  • State Management: Use useReducer to handle state.
    • State will include currentOperand, previousOperand, and operation.
  • Actions: Define different actions for the reducer.
    • ADD_DIGIT, CLEAR, DELETE_DIGIT, CHOOSE_OPERATION, EVALUATE
  • Digit Button Component: Create a reusable digit button component to handle digit inputs.
  • Operation Button Component: Create an operation button component for handling operations.
  • Edge Cases: Handle edge cases for digits and operations.
    • Prevent multiple zeros at the start or multiple decimal points.

Handling Various Operations

  • Choose Operation:
    • Update the state based on the chosen operation.
  • Equal (Evaluate) Operation:
    • Perform calculation and update the state.
    • Introduce an overwrite flag to handle overwriting behavior after evaluation.
  • Clear and Delete:
    • Implement CLEAR to reset state.
    • Implement DELETE_DIGIT to handle deleting digits.

Formatting Outputs

  • Number Formatting: Format numbers to include commas for better readability.
    • Separate integer and decimal portions.

Conclusion

  • Outcome: Successfully built a functional and styled calculator in React.
  • Recommendation: Check out the JavaScript-only version of the tutorial for further comparison and learning.