Josee
Josee

Reputation: 170

Getting an error stating that my state is undefined

I am trying to map out an array called answers which is located in my state. However, whenever I try to do so, I keep getting an error saying "cannot read property of 'answers' undefined".

constructor(props){
        super(props)

        this.state = {
            answers:[]
        }

        console.log(this.state.answers)
        this.answerList = this.answerList.bind(this)
    }

answerList = this.state.answers.map((answer)=>{
            return  <div>{answer}</div>
    })

 render(){
        return(
            <div className="list ui container">
                <div className="ui grid">
                    <div className="row centered"> 
                        { this.answerList}
                    </div>
                </div>
            </div>
        )
    }

I tried binding it, changing it into an arrow function and even putting in items inside the answers array, but I still get the same error. The only thing i can think of that is giving this error is that I am incorrectly binding something, or not binding it at all.

edit: When I changed it into an arrow function, I got an error stating that I can't have a function as a react child instead of saying answers is undefined, thus my thinking for this being a binding problem.

Upvotes: 0

Views: 33

Answers (1)

goto
goto

Reputation: 4425

You should take a little bit of a different approach and create your list of answers inside the render method, just before you do the return, like in the following example:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      answers: []
    };
  }

  render() {
    const answerList = this.state.answers.map(answer => {
      return <div>{answer}</div>;
    });

    return (
      <div className="list ui container">
        <div className="ui grid">
          <div className="row centered">{answerList}</div>
        </div>
      </div>
    );
  }
}

Upvotes: 1

Related Questions