Sandro Palmieri Sandro Palmieri - 3 years ago 162
Javascript Question

Input elements not updating in React

I am building a very basic React application but having some issues with form inputs:
My state:

class App extends Component {
constructor(){
super();
this.state = {
books: [],
book:{
author:"",
title: ""
}
}
this.handleInputChange = this.handleInputChange.bind(this)
}


My form:

<form onSubmit={this.addBook}>
<input
name="author"
type="text"
placeholder="author"
value={this.state.book.author}
onChange={this.handleInputChange}
/><br/>
<input
name="title"
type="text"
placeholder="title"
value={this.state.book.title}
onChange={this.handleInputChange}
/><br/>
<input type="submit" />
<button>Update</button>
<button>Delete</button>
</form>


My event handler:

handleInputChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}


Still I am not able to digit in the input field. When I try to digit a value nothing happens and the input field is not updating properly. Any suggestions?
Thanks

Answer Source

Your book state is state.book.title and state.book.author, so you need to specify in setState that it's the state.book object that you want to update with the event.target.value.

Hopefully this will do the trick:

handleInputChange(event) {
  this.setState({
    book: {
    ...this.state.book,
    [event.target.name]: event.target.value
    },
  });
}

When updating state for your nested book object, you need to make a copy of it, but with the property you want changed set to the new value. This is what the ellipsis notation helps with.

More info here: How do I setState for nested array?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download