I’m working on a React component where I want to update the state with the value entered in an input field. However, I’m encountering an issue where I’m unable to see what I’m typing in the input field, except for the last character.
function App() {
const [name, setName] = useState("");
let newName;
function handleChange(event) {
newName = event.target.value;
console.log(newName);
}
function handleClick() {
setName(newName);
}
return (
<div className="container">
<h1>Hello {name}</h1>
<input
onChange={handleChange}
type="text"
placeholder="What's your name?"
value={name}
/>
<button onClick={handleClick}>Submit</button>
</div>
);
}
I understand that the issue is related to the way the state is being updated, but I’m confused about why I can’t see the characters as I type. Even though handleChange is called and I can see the value in the console, the input field only displays the last typed character.
Could someone explain why this is happening and how I can fix it?
I expected that when handleChange was called, the console would print an empty string because the value of the input is bound to the name state, which is initially an empty string. However, I was surprised to see that only the last character typed was displayed in the input field.
3
Answers
if you what to use 2
useState
hooks then this method might helpYour code is not working as intended because you are setting the name state to a variable stored with the last value of the input field. What you want to do is update the state as characters are being typed into the field. The following revised code fixes the issue and should work just as expected.
You are setting input value to name, which is empty string. When handleChange will execute it will only take single key stroke value because we already set input with empty string (Which we called controlled input). Instead of using local variable you have to create another boolean state to toggle.