user1177440
user1177440

Reputation:

ReactJS - Custom Dropdown

I have a drop down that has a nested ul in ECMAScript 6.

Relevant code for dropdown:

 ......
   handleItemClicked(item){
     alert(item)
  }

   render(){
     return(
              ....
            <UnorderedList whenItemClicked={this.handleItemClicked} />
              ....
    )
}

Relevant code for unordered list:

    return(
        <ul>
           ....
            {this.props.dropItems.map(function(item){
                return (<li onClick={this.props.whenItemClicked(item)} key={item}><a>{item}</a></li>)
            }, this)}
        </ul>
    )

Result:

There are no errors, however, when the page is loaded the alert event starts immediately and loops for each item in the array. And clicking on a < li > afterwards DOES NOT produce an alert event.

What I want is for the alert to occur, not on page load, but as each respective < li > is clicked and only for the item's name, not the names in the entire array.

Any Ideas?

UPDATE:

Thanks crob, solution:

  return (<li onClick={this.props.whenItemClicked.bind(this, item)} style={listItemStyle} key={item}><a>{item}</a></li>)

Upvotes: 2

Views: 556

Answers (1)

Crob
Crob

Reputation: 15175

You are passing onClick={this.props.whenItemClicked(item)}, which is setting onclick to what is evaluated by the function whenItemClicked, not the actual function. This is what is causing the alerts.

To get around this, you could bind the function call to the item.

onClick={this.props.whenItemClicked.bind(this, item)}

But, perhaps a better solution would be to make a new component to represent the list item, and pass the whenItemClicked function through to that.

ListItem = React.createClass({
  handleClick: function() {
      this.props.onClick(this.props.item);
  },

  render: function() {
    return <li onClick={this.handleClick}>{item}</li>;
  }
})

Then your map would look like

return <ListItem onClick={this.props.whenItemClicked} item={item} />

Upvotes: 1

Related Questions