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 get the value from the function to call React

i am beginner of react. i want to return value inside the function. what i tried far i attached below.
here i want to add two numbers. it is working successfunny i checked through console.log(tot). but
tot variable i want to print it out inside the form here.

<p>
       {tot }   
</p>

but no out displayed i attached the full code below.

import { useState } from "react";

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

function Box() {

const [num1, setNum1] = useState();
const [num2, setNum2] = useState();
 let tot = 0;
function handleClick()
{
    tot = Number(num1) + Number(num2);
    console.log(tot);
}

return (
  <div className="box">

    <input type="text" name="num1" class="form-control" onChange={(event) =>
            {
              setNum1(event.target.value);      
            }}></input>
    <input type="text"   class="form-control" onChange={(event) =>
            {
              setNum2(event.target.value);      
            }}></input>
    
    <p>
           {tot }   
    </p>
   


    <button onClick={handleClick}  class="btn btn-warning"> Click Me</button>
    <h1>Box.....</h1>
   
  </div>
    
);

}

export default Box;

>Solution :

You need to use State to render the updated value. Without state change, react won’t re-render the updated value.
You can re-write the component as follows

....
const [num1, setNum1] = useState();
const [tot, setTot] =  useSate(0); // take tot in a state

// update the handle click function 
function handleClick()
{
    setTot(Number(num1) + Number(num2)); // set number to the state
}

....
 <p>
       {tot }   
 </p>
....

Hope this works!

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