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

2
  • 1
    Which part is not working exactly handleInputChange or addBook? Commented Oct 1, 2017 at 7:39
  • handleInputChange Commented Oct 1, 2017 at 8:00

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.