Basic Calculator Implemented in React

1. Create a new React application using the command npx create-react-app calculator-app. This will create a new directory with the basic file structure for a React application.

2. In the src directory, create a new component for the calculator called Calculator.js.

import React, { useState } from "react";

const Calculator = () => {
  const [num1, setNum1] = useState("");
  const [num2, setNum2] = useState("");
  const [operator, setOperator] = useState("");
  const [result, setResult] = useState("");

  const handleSubmit = (event) => {
    switch (operator) {
      case "add":
        setResult(+num1 + +num2);
      case "subtract":
        setResult(+num1 - +num2);
      case "multiply":
        setResult(+num1 * +num2);
      case "divide":
        if (num2 !== 0) {
          setResult(+num1 / +num2);
        } else {
          setResult("Cannot divide by zero!");
        setResult("You need to select a method!");

  return (
    <form onSubmit={handleSubmit}>
        onChange={(event) => setNum1(}
        placeholder="Number 1"
      <br />
        onChange={(event) => setNum2(}
        placeholder="Number 2"
      <br />
      <select value={operator} onChange={(event) => setOperator(}>
        <option value="">None</option>
        <option value="add">Add</option>
        <option value="subtract">Subtract</option>
        <option value="multiply">Multiply</option>
        <option value="divide">Divide</option>
      <br />
      <br />
      <button type="submit">Calculate</button>

export default Calculator;

3. In the src/index.js file, you need to import and render the Calculator component.

import React from 'react';
import ReactDOM from 'react-dom';
import Calculator from './Calculator';

ReactDOM.render(<Calculator />, document.getElementById('root'));

In this example, Calculator component using hooks for the state management. We are using the useState hook to create state variables num1, num2, operator, and result.

We have defined a handleSubmit function which will be called on the form submit. It will perform the calculation based on the operator selected and set the result in the result state. We have also added a form validation to check if user is dividing by zero or if user has not selected any operator.

The component renders a form with input fields for the numbers, a select dropdown for the operator, and a submit button. The input fields and select dropdown are controlled components, where the value of the input fields and the selected option are controlled by their respective state variables.

Finally, we are rendering the Calculator component inside the root element in our HTML file by calling the ReactDOM.render() method. Please note that this is just a basic example and you can enhance it further to add validation, error handling, and user-friendly feedback for invalid inputs.