import React from "react"
export default function Components() {
const PI = 3.14
const [value, setValue] = React.useState("")
const [inputvalue, setInputvalue] = React.useState(0)
function calculation() {
const originalvalue = PI * inputvalue * inputvalue
setValue(`${originalvalue} cm^2`)
console.log(value)
}
function getInput (event) {
setInputvalue(event.target.value)
}
console.log("main")
return (
<div className="output">
<h4>Enter the r of the circle below in cm</h4>
<input onChange={getInput} type="number" name="input"/>
<button onClick = {calculation}> Show Area</button>
<p>Area of the circle is : {value}</p>
</div>
)
}
So whenever I input a number my component is re-rendering(I checked it with a console log) but my output value which is a state value (Area of the circle is : {value}) still stays on the page. Instead When the component re-renders, it needs to be assigned as "" again. But it's not happening and my code is working fine. I just wanna understand how is this possible
CodePudding user response:
Your getInput
is updating inputvalue
, not value
.
To get your input element's onChange handler to update the UI content, getInput
needs to be something more like:
function getInput (event) {
setValue(event.target.value)
}