D Durham
D Durham

Reputation: 1341

React state array adding values

I'm sure it is something obvious and then I'll feel silly, but what am I missing here? I have something like:

export default class Questions extends Component {

  state = {
    questions: [{value: 'one'}, {value: 'two'}]
  };

  addQuestion = (question) => {
    let questions= this.state.questions
    let newQuestions = [...questions, {value: question}]
    this.setState({
      questions: newQuestions
    })
  };

  render() {
    return (
      <div>
        {this.state.questions.map((question, index) => <p key={index}>{question.value}</p>)}
        <button onClick={this.addQuestion.bind('three')}>Add</button>
      </div>
    )
  }

}

The initial state values show up fine, but when I click add I get a very long error from React about:

Uncaught Error: Invariant Violation: Objects are not valid as a React child...

So, what am I missing here?

Upvotes: 2

Views: 243

Answers (1)

Alexandr Lazarev
Alexandr Lazarev

Reputation: 12862

Most probably it should be:

{this.addQuestion.bind(this, 'three')}

Otherwise, you would not be able to access this.state in addQuestion:

let questions= this.state.questions

Upvotes: 2

Related Questions