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";

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!

Leave a Reply