0

I'm trying to add a click event inside a map function which is looping through an arraylist. For some reason the onClick is causing the following TypeError.

Cannot read property 'handleClick' of undefined

Thanks for your help!

var subcategories = {
title: ['item1', 'item2', 'item3', 'item4']
};

  handleClick(e, subCategoryTitle) {
e.preventDefault();
  this.setState({selected: subCategoryTitle});
}

renderSubCategory(){
  var data = [];

  for (var x = 0; x <= subcategories.title.length - 1; x++) {
    data.push(x)
  }

  var rowMap = data.map(function(index) {
    return(
      <BC.ListItem spacing="mini">
        <BC.Text onClick={this.handleClick.bind(this, subcategories.title[index])} textBold={this.state.selected === subcategories.title[index] ? true : false}>{subcategories.title[index]}</BC.Text>
      </BC.ListItem>
      )
  })
  return rowMap;

}
4
  • What does this give you if you do console.log(this)? My guess is the this you're trying to refer to is the tag and not data Commented Nov 13, 2015 at 17:20
  • 1
    Map has an option to pass this. data.map(function(){}, this). Commented Nov 13, 2015 at 17:36
  • 1
    By the way, just because the answer is the same doesn't mean the question is the same. Commented Nov 13, 2015 at 17:39
  • Thanks everyone. Seems like data.map(function() {...}, this) fixed the problem :) Commented Nov 13, 2015 at 17:46

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.