2

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?

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Yes - that was it. Still getting used to the lexical this binding provided by ES6 arrow functions and where this is or is not needed. Thank you sir!

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.