Skip to content
Advertisement

onChange doesn’t work when value of input clears

I have a problem in handling input’s value changing so here is my code in react,onChange works but when i clear the default value it doesn’t log anything until i do another change.

<Form.Control
  type="text"
  placeholder="name"
  defaultValue={this.state.name}
  onChange={e=>console.log(e.target.value)}
/>

I wrote console.log just for test.

Advertisement

Answer

Value is not changing because in reactjs component rerenders once state chages and using console.log on onChange does not update any change in state. so you have to update the state on onChange event,

Try following, I am assuming it is class component as you have used this.state.name

<Form.Control
  type="text"
  name="name"
  placeholder="name"
  defaultValue={this.state.name || ""}
  value={this.state.name}
  onChange={e=>this.setState({name:e.target.value})}
/>
Advertisement