import React, { useState } from "react";
function App() {
const [name, setName] = useState("");
const [headingText, setHeadingText] = useState("");
function handleChange(event) {
// console.log(event.target.value);
setName(event.target.value);
}
function handleClick(event) {
setHeadingText(name);
//after everything is done
event.preventDefault();
}
return (
<div className="container">
<h1>Hello {headingText}</h1>
<form onSubmit={handleClick}>
<input
onChange={handleChange}
type="text"
placeholder="What's your name?"
value={name}
/>
<button type="submit">Submit</button>
</form>
</div>
);
}
export default App;
I will use the above code for asking my question. input element handles its state change via user input(value attribute) but react uses state variable to handle state change. In order to have one constant value we set react variable to handle state change of form element as well.
value={name}
but if we do so and then access the value entered by the user through event.target.value, How is it able to track what user enters in the input field as we have set value={name}. Shouldn't event.target.value give us the value of name variable instead of user input