TheRogerLAB Codes

Create a calculator in ReactJS

  July, 2021

Introduction

This is an example of how to make a simple calculator using ReactJS. Click DEMO button to see this example with css styles. Feel free to modify the code and improve it.

Step 1: Define the component

class Calculator extends React.Component {
  constructor(props) {
  super(props);
  this.state = {printValue:"", memory:"", memoryState:""};
  this.print = this.print.bind(this);
  }
  print(param){
    var inScreen = this.state.printValue;
    if(param != "=")
      this.setState({printValue:inScreen + param});

    if(param == "="){
      this.setState({printValue:eval(inScreen)});
    }

    if(param == "AC")
      this.setState({printValue:""});

    if(param == "M"){
      if(this.state.memory == "" && inScreen!=""){
        this.setState({printValue: inScreen, memory:inScreen, memoryState:" activate"});
      } else {
        var w = this.state.memory;
        this.setState({printValue: w, memory:"", memoryState:""});
      }
    }
  }
  render(){
    return(
    <div className="calculator">
    <div>
    <input value={this.state.printValue}></input>
    </div>
    <div>
      <div>
        <button onClick={this.print.bind(this,"M")} className={"op"+this.state.memoryState}>M</button>
        <button onClick={this.print.bind(this,"(")} className="op">(</button>
        <button onClick={this.print.bind(this,")")} className="op">)</button>
        <button onClick={this.print.bind(this,'AC')} className="op">AC</button>
      </div>
      <div>
        <button onClick={this.print.bind(this,"7")}>7</button>
        <button onClick={this.print.bind(this,"8")}>8</button>
        <button onClick={this.print.bind(this,"9")}>9</button>
        <button onClick={this.print.bind(this,"/")} className="op">/</button>
      </div>
      <div>
        <button onClick={this.print.bind(this,"4")}>4</button>
        <button onClick={this.print.bind(this,"5")}>5</button>
        <button onClick={this.print.bind(this,"6")}>6</button>
        <button onClick={this.print.bind(this,"*")} className="op">*</button>
      </div>
      <div>
        <button onClick={this.print.bind(this,"1")}>1</button>
        <button onClick={this.print.bind(this,"2")}>2</button>
        <button onClick={this.print.bind(this,"3")}>3</button>
        <button onClick={this.print.bind(this,"-")} className="op">-</button>
      </div>
      <div>
        <button onClick={this.print.bind(this,"0")}>0</button>
        <button onClick={this.print.bind(this,".")} className="op">.</button>
        <button onClick={this.print.bind(this,"=")} className="op iqual">=</button>
        <button onClick={this.print.bind(this,"+")} className="op">+</button>
      </div>
    </div>
    </div>
    );
  }
}

Check a working demo for this code:

SEE DEMO RATE THIS ARTICLE
4.8
13
TheRogerLAB Codes
Powered by TheRogerLAB Sandbox

info@therogerlab.com