Miguel Victor
Miguel Victor

Reputation: 135

reactjs passing a callback results in undefined

I'm tring to build an exam generator using React v0.13.3. The problem is when i click Add a choice, the callback function I passed as a prop to the Question element is undefined. Here is the full snippet.

By the way, i've pasted the transformed script and should you want the jsx script. here it is not-yet-transformed.js

http://jsfiddle.net/acqwg429/

Upvotes: 0

Views: 995

Answers (2)

fixmycode
fixmycode

Reputation: 8506

Following pashaplus' answer, you could also pass the context argument to the map function like this:

var questions = this.state.questions.map(function (question, index) {
    return (
        <Question 
            key={index} 
            index={index} 
            src={question} 
            handleAddChoice={this.onAddChoice} />
    );
}, this);

Upvotes: 1

pashaplus
pashaplus

Reputation: 3706

It is because in your Exam component's map function inside render method this keyword is not refering to the Exam component object. you can either fix issue with Es6 arrow function or create local variable called _this and assign this to _this before map function

with arrow function

    var questions = this.state.questions.map((question, index) =>{
        return (
            React.createElement(Question, {
                key: index, 
                index: index, 
                src: question, 
                handleAddChoice: this.onAddChoice})
        );
    });

jsfiddle http://jsfiddle.net/jkwhrs1j/

With local variable assignment jsfiddle http://jsfiddle.net/gzevgjfb/

Upvotes: 1

Related Questions