Published January 02, 2025

Click Events in React Js

Mastering Click Events in React: Build a Simple Calculator Step-by-Step

image

Learn how to build a simple calculator using React's click events. This step-by-step guide covers React event handling, state management with useState, and implementing essential calculator functionalities. Perfect for beginners looking to strengthen their React skills!

React.js Tutorial: Build a Simple Calculator Using Click Events

Welcome to this step-by-step guide on building a simple calculator in React.js. In this tutorial, we will explore how to use React's useState hook and handle click events to create a functional calculator. This guide is perfect for beginners looking to strengthen their understanding of React components and event handling.


What You Will Learn

  1. Introduction to useState in React

  2. Handling click events effectively

  3. Designing a clean JSX structure

  4. Building a functional calculator

  5. Error handling and reset functionality


Getting Started

Before we dive into the code, ensure you have the following:

  • A basic understanding of React.js

  • Node.js installed on your system

  • A code editor (e.g., VS Code)


Step 1: Setting Up the Project

  1. Create a new React app using the command:

    npx create-react-app simple-calculator
  2. Navigate to the project directory:

    cd simple-calculator
  3. Open the project in your favorite code editor.


Step 2: Import React and useState

React and useState are essential for managing the component's state. Import them at the top of your file:

import React, { useState } from 'react';

Step 3: Create the Component Function

Define a functional component called SimpleCalculator to house your calculator's logic and UI.

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

  // Handle number or operator clicks
  const handleClick = (value) => {
    setInput(input + value);
  };

  // Perform calculation
  const handleCalculate = () => {
    try {
      setInput(eval(input).toString());
    } catch (error) {
      setInput('Error');
    }
  };

  // Clear the input
  const handleClear = () => {
    setInput('');
  };

  return (
    <div>
      <h1>Simple Calculator</h1>
      <input type="text" value={input} readOnly />
      <div>
        <button onClick={() => handleClick('1')}>1</button>
        <button onClick={() => handleClick('2')}>2</button>
        <button onClick={() => handleClick('3')}>3</button>
        <button onClick={() => handleClick('+')}>+</button>
      </div>
      <div>
        <button onClick={() => handleClick('4')}>4</button>
        <button onClick={() => handleClick('5')}>5</button>
        <button onClick={() => handleClick('6')}>6</button>
        <button onClick={() => handleClick('-')}>-</button>
      </div>
      <div>
        <button onClick={() => handleClick('7')}>7</button>
        <button onClick={() => handleClick('8')}>8</button>
        <button onClick={() => handleClick('9')}>9</button>
        <button onClick={() => handleClick('*')}>*</button>
      </div>
      <div>
        <button onClick={() => handleClick('0')}>0</button>
        <button onClick={handleClear}>C</button>
        <button onClick={() => handleClick('/')}>/</button>
        <button onClick={handleCalculate}>=</button>
      </div>
    </div>
  );
};

export default SimpleCalculator;

Step 4: Understanding the Code

1. State Setup

We use the useState hook to manage the calculator's input:

const [input, setInput] = useState('');
  • input: Stores the current input or result.

  • setInput: Updates the input state.

2. Event Handlers

  • handleClick: Appends the clicked value (number or operator) to the input.

  • handleCalculate: Evaluates the input using eval() and updates the result. If there’s an error, it displays "Error."

  • handleClear: Resets the input to an empty string.

3. JSX Structure

The JSX structure includes:

  • An input field to display the current input or result.

  • Buttons for numbers, operators, and actions (clear and calculate).

 


Conclusion

Congratulations! You have successfully built a functional calculator using React. This project demonstrates how to use useState and handle click events effectively. Feel free to extend the functionality, such as adding advanced operations or improving the UI.


Additional Resources

Stay tuned for more React tutorials and project ideas! Happy coding!


 #React #ClickEvents #useState #ReactCalculator #FrontendDevelopment

 

Download Lecture Pdf..

Reviews

Leave a Comment