Search code examples
reactjsreact-bootstrapcreate-react-app

Event handler for onClick in create-react-app gives TypeError undefined


I am creating a project using create-react-app for the first time. I am using react-bootstrap for UI. I have a simple App.js component

import ListGroup from 'react-bootstrap/lib/ListGroup';
import ListGroupItem from 'react-bootstrap/lib/ListGroupItem';

class App extends Component {

   constructor(props) {
     super(props);
     this.handleClick = this.handleClick.bind(this);
   }

   handleClick(e) {
      this.setState({ clicked: true})
   }

   render() {
      {this.state.response.map(function(object) {
        return (
          <ListGroup>
            <ListGroupItem  onClick={  this.handleClick }>{object.name}
            </ListGroupItem>
          </ListGroup>
        );
      })}
   }
}

I keep getting an error

TypeError: Cannot read property 'handleClick' of undefined

Could anyone help please?


Solution

  • Use an arrow function for the map callback to preserve this binding to your class:

      this.state.response.map((object) => {
        return (
          <ListGroup>
            <ListGroupItem  onClick={  this.handleClick }>{object.name}
            </ListGroupItem>
          </ListGroup>
        );
      })
    

    You should also make your handler an arrow function to preserve this binding:

       handleClick = (e) => {
          this.setState({ clicked: true})
       }