onChange doesn't work when value of input clears

Viewed 1816

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.

4 Answers

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})}
/>

Updated

Try with uncontrolled input:

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

Use value instead of default value:

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

Try using an empty value instead of giving it null

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