Home > Back-end >  how to get the value from the function to call React
how to get the value from the function to call React

Time:09-26

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"  onChange={(event) =>
            {
              setNum1(event.target.value);      
            }}></input>
    <input type="text"    onChange={(event) =>
            {
              setNum2(event.target.value);      
            }}></input>
    
    <p>
           {tot }   
    </p>
   


    <button onClick={handleClick}  > Click Me</button>
    <h1>Box.....</h1>
   
  </div>
    
);

}

export default Box;

CodePudding user response:

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!

CodePudding user response:

`const [tot, setTot] =  useSate(0); 
function handleClick()
{
    // you were not updating the state, if there is a change so you have to re- 
    // render 
    so that browser can show the change.
 tot = Number(num1)   Number(num2);
 setTot(tot); 
}`
  • Related