Bomber
Bomber

Reputation: 10957

ReactJS - Call to function from map function, function not defined

I am trying to call getElementByKey() function where I map a collection:

{this.state.sections.map(function(section) {
                return (<Tab key={section.value} title={section.label}>
                        {this.getElementByKey(section.name)}
                </Tab>);
            })}

Here is the method I'm trying to call:

getElementByKey: function(name){

    switch(name) {
        case "EditStudentBasicDetails":
            return <EditStudentBasicDetails studentId={this.state.studentId} sectionData={this.state.studentData.activeData.basicDetails} />;
        case "EditStudentAgentsInfo":
            return <EditStudentAgentsInfo  studentId={this.state.studentId} sectionData={this.state.studentData.activeData.agentsInfo} />;
        case "EditStudentCaseNotes":
            return <EditStudentCaseNotes studentId={this.state.studentId} sectionData={this.state.studentData.activeData.caseNotes}/>;
        case "EditStudentRegistration":
            return <EditStudentRegistration studentId={this.state.studentId} sectionData={this.state.studentData.activeData.registration} />;
        case "EditStudentContactDetails":
            return <EditStudentContactDetails studentId={this.state.studentId} sectionData={his.state.studentData.activeData.contactDetails} />;
        case "EditStudentAttendance":
            return <EditStudentAttendance studentId={this.state.studentId} sectionData={this.state.studentData.activeData.attendance} />;
        case "EditStudentSENDetails":
            return <EditStudentSENDetails studentId={this.state.studentId} sectionData={this.state.studentData.activeData.SENDetails} />;
        case "EditStudentSENReviews":
            return <EditStudentSENReviews studentId={this.state.studentId} sectionData={this.state.studentData.activeData.SENReviews} />;

        default:{

        }
    }

},

I get the error, this.getElementByKey is not a function, can anyone please help?

Upvotes: 0

Views: 52

Answers (1)

Henrik Andersson
Henrik Andersson

Reputation: 47172

As it stands your this is the mapping function and not the component as you might suspect.

.map() takes a second argument, which will set the context of the mapping function to whatever object is being passed.

.map(function () {}, this);

Or you can use .bind() to change the meaning of this.

this.state.sections.map(function() {}.bind(this));

Upvotes: 3

Related Questions