Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to do Addition inside a addClick function

Please help me out what to do here to make addition of two numbers. When I click on addClick function, it is not making addition.
when I type 2 and 2, it is showing 22 not 4.
please help me out what to do here.
I am new here.

App.jsx:

import React, {useState} from 'react';

function App(){

  const [number1, setNumber1] = useState('');
  const [number2, setNumber2] = useState('');
  const [headingText, setHeading] = useState('');

  function handleChange(event) {
    setNumber1(event.target.value);
    setNumber2(event.target.value);

  }

  function addClick(event){
    let sum;
    sum = number1 + number2;
    setHeading(sum);
    event.preventDefault();
  }


  return (
    <div>
      <form>
        <label htmlFor="number1">Number1</label>
        <input onChange={handleChange} type="number"/>
        <label htmlFor="number2">Number2</label>
        <input onChange={handleChange} type="number"/>
        <button onClick={addClick} type="submit">Add</button>
        <button type="submit">Subtract</button>
        <button type="submit">Multiplication</button>
        <button type="submit">Division</button>
        <h1>Result: {headingText}</h1>
      </form>
    </div>
  );
}
export default App;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You don’t really need to use form here, since you store the values in state, you can just perform the tasks easily like so.

<button onClick={addClick}>Add</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading