Swapna
Swapna

Reputation: 843

Can't read property of "handleClick" of undefined React JS

I have been trying to add a new class to a div with class option using state of React. To note , I am a beginner in React.

Here is my code. handleClick() is declared followed after constructor class. bind(this) is included to not to loose where this points to. I want to understand why I am still getting type error with a message "handleClick" as undefined.

import React, { Component } from 'react';
import {Grid, Col, Row, Button} from 'react-bootstrap';
import facebook_login_img from '../../assets/common/facebook-social-login.png';

const profilesCreatedBy = ['Self' , 'Parents' , 'Siblings' , 'Relative' , 'Friend'];

class Register extends Component {

  constructor(props) {
    super(props);
    this.state = { addClass: false };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState({ addClass: !this.state.addClass });
  }

  render() {

    let selectOption = ["option"];
    if (this.state.addClass) {
      selectOption.push("option-active");
    }

    return (
        <section className="get-data__block" style={{padding: '80px 0 24px 0'}}>
          <Grid>
            <Row>
              <Col sm={10} md={8} mdOffset={2} smOffset={1}>
                <p className="grey-text small-text m-b-32"><i>
                    STEP 1 OF 6 </i>
                </p>

                <div className="data__block">

                    <div className="step-1">
                     <p className="m-b-32">This profile is being created by</p>
                      <Row>
                       {profilesCreatedBy.map(function(profileCreatedBy, index){
                          return  <Col className="col-md-15">
                                    <div onClick={this.handleClick} className={selectOption.join(" ")}>
                                        {profileCreatedBy}
                                    </div>
                                  </Col>;
                        })}
                      </Row>
                    </div>

                </div>

              </Col>
            </Row>
          </Grid>
        </section>
    );
  }
}

export default Register;

Upvotes: 1

Views: 1127

Answers (1)

Dev
Dev

Reputation: 3932

Try this:

{profilesCreatedBy.map((profileCreatedBy, index) => {
         return  <Col className="col-md-15">
                    <div onClick={this.handleClick} className={selectOption.join(" ")}>
                          {profileCreatedBy}
                    </div>
                 </Col>;
 })}

ES6 arrow function automatically preserves the current this context. For more explanation on context please have a look at this answer

Upvotes: 3

Related Questions