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.
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.
Share Improve this question edited Jul 18, 2021 at 4:41 mostafa asked Jul 18, 2021 at 4:27 mostafamostafa 711 silver badge7 bronze badges 6-
3
conosle.log
Don't you think there is a typo here – DecPK Commented Jul 18, 2021 at 4:28 -
you wrote
conosle.log
instead ofconsole.log
– user14779090 Commented Jul 18, 2021 at 4:34 -
There is a typo mistake in
console.log
– Sanket Shah Commented Jul 18, 2021 at 4:42 - yes i changed it but still doesn't work – mostafa Commented Jul 18, 2021 at 4:42
-
The
onChange
event occurs when the contents of the input are changed and focus is moved out from the input. When you clear thename
the contents change but the focus is still on input and so it does not fire onChange event. I guess maybe this will answer your question. You can try usingvalue
instead ofdefaultValue
– Sanket Shah Commented Jul 18, 2021 at 4:49
4 Answers
Reset to default 2Value is not changing because in reactjs ponent 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 ponent 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})}
/>
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)}
/>
Updated
Try with uncontrolled input:
<Form.Control
type="text"
placeholder="name"
onChange={(e) => console.log(e.target.value)}
/>