Codementor Events

How To Build A Simple Calculator Application With React.JS

Published Sep 10, 2018Last updated Mar 09, 2019

This is my approach to building a calculator with react.js. You can see the final result here.

Here’s the source code at github — https://github.com/niinpatel/calculator-react

First we’ll run the create-react-app command on our directory to create a basic react boilerplate application. Then we’ll jump right on to building our components.

This calculator application will need two components. One is our Result component where we display the output, and the other is KeypadComponent where we need to display our keypad.

In the src folder, we’ll create a directory called components. This is where we will code our components. Go into that folder and create ResultComponent.js.

This is what the code would look like.

import React, {Component} from 'react';

class ResultComponent extends Component {


    render() {
        let {result} = this.props;
        return (
            <div className="result">
                <p>{result}</p>
            </div>
    )
        ;
    }
}


export default ResultComponent;

Our result component consists of just one <p> tag which displays content from props. Next, let’s build a keypad component. Our keypad is just a bunch of buttons which do something when clicked. This is the code for our KeypadComponent.js file.

import React, {Component} from 'react';

class KeyPadComponent extends Component {

    render() {
        return (
            <div className="button">
                <button name="(" onClick={e => this.props.onClick(e.target.name)}>(</button>
                <button name="CE" onClick={e => this.props.onClick(e.target.name)}>CE</button>
                <button name=")" onClick={e => this.props.onClick(e.target.name)}>)</button>
                <button name="C" onClick={e => this.props.onClick(e.target.name)}>C</button><br/>


                <button name="1" onClick={e => this.props.onClick(e.target.name)}>1</button>
                <button name="2" onClick={e => this.props.onClick(e.target.name)}>2</button>
                <button name="3" onClick={e => this.props.onClick(e.target.name)}>3</button>
                <button name="+" onClick={e => this.props.onClick(e.target.name)}>+</button><br/>


                <button name="4" onClick={e => this.props.onClick(e.target.name)}>4</button>
                <button name="5" onClick={e => this.props.onClick(e.target.name)}>5</button>
                <button name="6" onClick={e => this.props.onClick(e.target.name)}>6</button>
                <button name="-" onClick={e => this.props.onClick(e.target.name)}>-</button><br/>

                <button name="7" onClick={e => this.props.onClick(e.target.name)}>7</button>
                <button name="8" onClick={e => this.props.onClick(e.target.name)}>8</button>
                <button name="9" onClick={e => this.props.onClick(e.target.name)}>9</button>
                <button name="*" onClick={e => this.props.onClick(e.target.name)}>x</button><br/>


                <button name="." onClick={e => this.props.onClick(e.target.name)}>.</button>
                <button name="0" onClick={e => this.props.onClick(e.target.name)}>0</button>
                <button name="=" onClick={e => this.props.onClick(e.target.name)}>=</button>
                <button name="/" onClick={e => this.props.onClick(e.target.name)}>÷</button><br/>
            </div>
        );
    }
}


export default KeyPadComponent;

Since we need to send the click event to the parent ( with information about which button was clicked), we will call this.props.OnClick function on every button click and pass e.target.name as an argument.

We’ll define the logic of that function into our parent component, which is App.js.

In the App.js file, which is the parent of all our previous components and which renders all the main components, we will include all the child components first. We will also include “result” variable in this.state which is passed into our result component. This will allow us to manipulate our display.

import React, { Component } from 'react';
import './App.css';
import ResultComponent from './components/ResultComponent';
import KeyPadComponent from "./components/KeyPadComponent";

class App extends Component {
    constructor(){
        super();

        this.state = {
            result: ""
        }
    }

    render() {
        return (
            <div>
                <div className="calculator-body">
                    <h1>Simple Calculator</h1>
                    <ResultComponent result={this.state.result}/>
                    <KeyPadComponent onClick={this.onClick}/>
                </div>
            </div>
        );
    }
}

export default App;

Notice that I have passed this.onClick into Keypad component but I haven’t defined it yet. Before defining that function, we need to do a few things. We need to create functions for our basic calculator features. In this calculator, I’ll have three main features.

this.Calculate => Calculate the result of our expression, this is triggered, when “=” button is pressed.

this.Reset => Clear our output, this is trigered when “C” is pressed.

this.Backspace => Clear the last character that was pressed. triggered on “CE”.

Let’s create those functions first.

import React, { Component } from 'react';
import './App.css';
import ResultComponent from './components/ResultComponent';
import KeyPadComponent from "./components/KeyPadComponent";

class App extends Component {
    constructor(){
        super();

        this.state = {
            result: ""
        }
    }
    

    calculate = () => {
        try {
            this.setState({
                // eslint-disable-next-line
                result: (eval(this.state.result) || "" ) + ""
            })
        } catch (e) {
            this.setState({
                result: "error"
            })

        }
    };

    reset = () => {
        this.setState({
            result: ""
        })
    };

    backspace = () => {
        this.setState({
            result: this.state.result.slice(0, -1)
        })
    };

    render() {
        return (
            <div>
                <div className="calculator-body">
                    <h1>Simple Calculator</h1>
                    <ResultComponent result={this.state.result}/>
                    <KeyPadComponent onClick={this.onClick}/>
                </div>
            </div>
        );
    }
}

export default App;

Finally, we can create our onClick function and include it in our App.js file.

Let’s do this.

import React, { Component } from 'react';
import './App.css';
import ResultComponent from './components/ResultComponent';
import KeyPadComponent from "./components/KeyPadComponent";

class App extends Component {
    constructor(){
        super();

        this.state = {
            result: ""
        }
    }

    onClick = button => {

        if(button === "="){
            this.calculate()
        }

        else if(button === "C"){
            this.reset()
        }
        else if(button === "CE"){
            this.backspace()
        }

        else {
            this.setState({
                result: this.state.result + button
            })
        }
    };


    calculate = () => {
        try {
            this.setState({
                // eslint-disable-next-line
                result: (eval(this.state.result) || "" ) + ""
            })
        } catch (e) {
            this.setState({
                result: "error"
            })

        }
    };

    reset = () => {
        this.setState({
            result: ""
        })
    };

    backspace = () => {
        this.setState({
            result: this.state.result.slice(0, -1)
        })
    };

    render() {
        return (
            <div>
                <div className="calculator-body">
                    <h1>Simple Calculator</h1>
                    <ResultComponent result={this.state.result}/>
                    <KeyPadComponent onClick={this.onClick}/>
                </div>
            </div>
        );
    }
}

export default App;

The onclick function simple, reads the argument, which is name of the button clicked, and changes the state appropriately depending on the input that is passed.

Finally, you can add a little bit of CSS to make it look nicer.

With this we have completed our Calculator Application with React.JS.

Final code — https://github.com/niinpatel/calculator-react/

Live at — https://calculator-n.herokuapp.com

Discover and read more posts from Nitin Patel
get started
post commentsBe the first to share your opinion
alex6255
a month ago

You can also get the same result with the above shared code here at
https://parcelstrackings.com/jaipur-golden-tracking/

alex6255
2 months ago

Here’s an alternative approach for creating a simple calculator application using React.JS:

  1. Begin by setting up your development environment with Node.js and NPM.

  2. Create a new React project named “calculator-app” by running the following command in your terminal:

npx create-react-app calculator-app
  1. Navigate into the newly created project directory:
cd calculator-app
  1. Open the src folder and create two new files: Calculator.js and Display.js.

  2. In Calculator.js, define the Calculator component:

import React, { useState } from 'react';
import Display from './Display';

const Calculator = () => {
    const [displayValue, setDisplayValue] = useState('');

    const handleButtonClick = (value) => {
        setDisplayValue(displayValue + value);
    };

    const handleClear = () => {
        setDisplayValue('');
    };

    const handleCalculate = () => {
        try {
            const result = eval(displayValue);
            setDisplayValue(result.toString());
        } catch (error) {
            setDisplayValue('Error');
        }
    };

    return (
        <div className="calculator">
            <Display value={displayValue} />
            <div className="buttons">
                <button onClick={handleClear}>C</button>
                <button onClick={() => handleButtonClick('/')}>&divide;</button>
                <button onClick={() => handleButtonClick('*')}>&times;</button>
                <button onClick={() => handleButtonClick('7')}>7</button>
                <button onClick={() => handleButtonClick('8')}>8</button>
                <button onClick={() => handleButtonClick('9')}>9</button>
                <button onClick={() => handleButtonClick('-')}>-</button>
                <button onClick={() => handleButtonClick('4')}>4</button>
                <button onClick={() => handleButtonClick('5')}>5</button>
                <button onClick={() => handleButtonClick('6')}>6</button>
                <button onClick={() => handleButtonClick('+')}>+</button>
                <button onClick={() => handleButtonClick('1')}>1</button>
                <button onClick={() => handleButtonClick('2')}>2</button>
                <button onClick={() => handleButtonClick('3')}>3</button>
                <button onClick={handleCalculate}>=</button>
                <button onClick={() => handleButtonClick('0')}>0</button>
            </div>
        </div>
    );
};

export default Calculator;
  1. In Display.js, define the Display component:
import React from 'react';

const Display = ({ value }) => {
    return (
        <div className="display">
            {value}
        </div>
    );
};

export default Display;
  1. Import and use the Calculator component in the App.js file:
import React from 'react';
import './App.css';
import Calculator from './Calculator';

function App() {
  return (
    <div className="App">
      <Calculator />
    </div>
  );
}

export default App;
  1. Run the React application using:
npm start

This approach creates a basic calculator application with buttons for numbers, operators, and the ability to clear the display and perform calculations and visit us for more codes on fitness https://bungeefitnessnearme.com/

alex6255
2 months ago

To create a basic calculator application using React.JS, you can proceed with the following steps:

  1. Prepare your development environment: Begin by installing Node.js and NPM on your machine. These can be obtained from the official website.

  2. Initiate a new React project: Open your terminal and execute the command “npx create-react-app calculator-app” to set up a new React project. This command will create all the necessary files and dependencies for your project.

  3. Define the calculator components: Establish two components, namely Calculator and Display. The Calculator component will manage the calculator’s logic, while the Display component will render the output.

import React from 'react';

const Calculator = () => {
    return (
        <div className="calculator">
            <Display />
        </div>
    );
};

const Display = () => {
    return (
        <div className="display">
            0
        </div>
    );
};

export default Calculator;
  1. Incorporate state management: Within the Calculator component, introduce state to retain the current and previous values, as well as the operator being used.
import React, { useState } from 'react';

const Calculator = () => {
    const [currentValue, setCurrentValue] = useState(0);
    const [previousValue, setPreviousValue] = useState(null);
    const [operator, setOperator] = useState(null);

    return (
        <div className="calculator">
            <Display value={currentValue} />
        </div>
    );
};

const Display = ({ value }) => {
    return (
        <div className="display">
            {value}
        </div>
    );
};

export default Calculator;
  1. Implement functions for button interactions: Create functions to manage clicks on number and operator buttons. These functions will update the calculator’s state accordingly.
const Calculator = () => {
    const [currentValue, setCurrentValue] = useState(0);
    const [previousValue, setPreviousValue] = useState(null);
    const [operator, setOperator] = useState(null);

    const handleNumberClick = (number) => {
        if (currentValue === 0) {
            setCurrentValue(number);
        } else {
            setCurrentValue(currentValue.toString() + number.toString());
        }
    };

    const handleOperatorClick = (operator) => {
        setOperator(operator);
        setPreviousValue(currentValue);
        setCurrentValue(0);
    };

    return (
        <div className="calculator">
            <Display value={currentValue} />
            <div className="buttons">
                {/* Button components */}
            </div>
        </div>
    );
};

Continue creating functions for button clicks and incorporate them into your button components. This will allow users to interact with your calculator application effectively just like https://jollibeemenuprices.com/

Show more replies