Why can't I change my input value in React even with the onChange listener
Unlike in the case of Angular, in React.js you need to update the state manually. You can do something like this:
<input
className="form-control"
type="text" value={this.state.name}
id={'todoName' + this.props.id}
onChange={e => this.onTodoChange(e.target.value)}
/>
And then in the function:
onTodoChange(value){
this.setState({
name: value
});
}
Also, you can set the initial state in the constructor of the component:
constructor (props) {
super(props);
this.state = {
updatable: false,
name: props.name,
status: props.status
};
}
You can do shortcut via inline function if you want to simply change the state variable without declaring a new function at top:
<input type="text" onChange={e => this.setState({ text: e.target.value })}/>
I think it is best way for you.
You should add this: this.onTodoChange = this.onTodoChange.bind(this)
.
And your function has event param(e)
, and get value:
componentWillMount(){
this.setState({
updatable : false,
name : this.props.name,
status : this.props.status
});
this.onTodoChange = this.onTodoChange.bind(this)
}
<input className="form-control" type="text" value={this.state.name} id={'todoName' + this.props.id} onChange={this.onTodoChange}/>
onTodoChange(e){
const {name, value} = e.target;
this.setState({[name]: value});
}