Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
Simple Calculator Using React

I am trying to build a very simple calculator that just takes the input from two text boxes, and adds the values together when you press the Add button and subtracts the two values when you press the subtract button. The total should output to a third text box. This is what I have so far:

import React, { useState } from 'react';
import './App.css';
class Calculator extends React.Component{
  constructor(){
    super();
    this.state={
      number1:"",
      number2:"",
      total: ""
    }
  }
handlenumber1 = (event) => {
  this.setState({number1:event.target.value})
}
handlenumber2 = (event) => {
  this.setState({number2:event.target.value})
}


exe = (e) => {
  e.preventDefault();
  this.setState({total: parseInt(this.state.number1) + parseInt(this.state.number2)})
}


  render(){
    return( 
    <div>
      <h1>Simple Calculator</h1>
      <form onSubmit={this.exe}>
      <div>
      Number 1: 
      <input type="text" value={this.state.number1} onChange={this.handlenumber1}/>
      </div>
      <div>
      Number 2: 
      <input type="text" value={this.state.number2} onChange={this.handlenumber2}/>
      </div>
      <div>
      <button type= "submit"> Add </button>
      </div>
      <div>
      <button type= "submit"> Subtract </button>
      </div>
      </form>
      <input type = "text" name = "name" value = {this.state.total}/>
      </div>
    )
  }

}

export default Calculator;

As of now, I am able to get the addition output to the textbox but I am confused on getting the subtraction output to the same textbox using a different button. I assume I would use something like this.setState({total: parseInt(this.state.number1) - parseInt(this.state.number2) but I am unsure of how to get it into the same textbox. Thanks in advance!

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!