dorkycam
dorkycam

Reputation: 529

React TypeError: Cannot read property 'bind' of undefined

        <div className="questions" id="questions">
          {Array(this.state.numQuestions).fill().map((number, questionIdx) => {
            return (
              <div> 
                <label>Question</label>
              <input type="text" onChange={this.handleQuestionChange.bind(questionIdx)}  />
              </div>);
          Array(4).fill().map((number, index) => {
          return <input type="text" key={index} onChange={this.handleAnswerChange.bind(questionIdx)}  />
          })}
          )
          })}
        </div>

I am getting a strange error for the line <input type="text" onChange={this.handleQuestionChange.bind(questionIdx)} />

I'm not quite sure what the error means let alone how to fix it, here's the error information:

TypeError: Cannot read property 'bind' of undefined

Thanks!

Upvotes: 0

Views: 3280

Answers (2)

haotian yang
haotian yang

Reputation: 1

I prefer the arrow function, it's more elegant. Just simply define it like:

const handleAnswerChange = (index) => {
  // do anything you like
  console.log(index)
  }

Then you don't have to bind your function. It's already worked.

Upvotes: 0

SLaks
SLaks

Reputation: 887195

It means that this.handleQuestionChange is undefined, so you can't call bind() (or anything else) on it.

Check your object / functions and make sure it exists.

Upvotes: 1

Related Questions