2

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

Sandro Palmieri
  • 1,193
  • 2
  • 12
  • 26

2 Answers2

2

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?

Paul Calcraft
  • 923
  • 6
  • 11
1

The title/author properties are within the book object. It looks like you're only referencing state.author or state.title, but you need to reference state.book.title or state.book.author. Try this:

handleInputChange(event) {
    this.setState({
      book[event.target.name]: event.target.value
    });
  }
Dream_Cap
  • 2,292
  • 2
  • 18
  • 30