import { useState } from "react";
import "./styles.css";
function App() {
const [InputVal, setInputVal] = useState();
const [ShowDiv, setShowDiv] = useState(
<div>
<p>Hello world. This is default "Show Div" value</p>
</div>
);
const ChangeDivFunc = () => {
setShowDiv(
<div>
<p style={{ color: "red" }}>
Hello World. This is updated "Show Div" value
</p>
<input onChange={getInputval} type="text" />
<br />
<br />
<button onClick={AlertVal}>Show Input Value</button>
</div>
);
};
const getInputval = (val) => {
setInputVal(val.target.value);
};
const AlertVal = () => {
alert(InputVal);
};
return (
<div className="App">
<h1>Example</h1>
<br />
<button onClick={ChangeDivFunc}>Change Div</button>
{ShowDiv}
</div>
);
}
export default App;
Code Flow:
- Click Change Div button then it will show Input field and Show Input Value button.
- Now, Enter some value in input field and click the Show Input Value button to get the value of input field.
Problem: It returns undefined instead of input field value.
I'm trying to get the value of Input field when Show Input Value button is clicked. But I'm not getting the desired results.
Here's the Sandbox link : Click for Code