john doe
john doe

Reputation: 9660

onChange React Move Value into Object

I have the following code:

  handleTextChange = (e) => {

    this.setState({
        [e.target.name] : e.target.value
    })

  }

  render() {
    return (
      <div>
        <h1>Add Movie</h1>
        <input type="text" name="name" onChange={this.handleTextChange} placeholder="Enter movie name" />
        <input type="text" name="year" onChange={this.handleTextChange} placeholder= "Enter movie year" />

Whenever I type the state creates a new property based on the name of the input field and assign the value in the textbox. This works fine and I end up with:

state = {
  name : "Movie Name", 
  year : "1992"
}

How can I end up with something like this:

state = {

    movie: { 
     name : "Movie Name", 
     year : "1992"
} 
}

Upvotes: 0

Views: 28

Answers (1)

nanobar
nanobar

Reputation: 66355

You just want to set it in an object with a static name?

this.setState(state => ({
  movie: {
    ...state.movie,
    [e.target.name]: e.target.value
  }
}));

PS Your initial state should have movie: {} otherwise the spread will throw an exception.

Upvotes: 1

Related Questions