Brian J Brian J - 2 months ago 11
React JSX Question

How to pass parameters in onClick event bind?

I've set up an

onClick
event in a ListItem. Then called
.bind
on the method invoked to pass in the clicked list item's id and name values.

The following SO question suggested using bind but it seems adding the onCLick event to the ListItem breaks the list binding.

Before adding the click event the list span binding to the
asset.name
is working as expected and the list is populated.

Also if I try
onClick={this._onAssetSelected()
with no parameters the click event doesn't work.

Question:

How can you pass parameters in an onClick event bind in JSX?

List definition:

<List selectable={true} selected={0}>
{

this.state.data.map(function (asset) {
return (
<ListItem justify="between" onClick={this._onAssetSelected.bind(this, asset.name, asset.id)} >
<span>{asset.name}</span>
</ListItem>
);
})

}
</List>


Method called from the click event:

_onAssetSelected(assetName, assetID) {

console.log(assetName);
console.log(assetID);


}

Answer

You can do this. Define an anonymous function as the callback, inside which you call your method with the parameters. Hop ut helps!

<List
  selectable={true}
  selected={0}>  
  {

    this.state.data.map(function (asset) {
        return (
            <ListItem
              justify="between"
              onClick={(e) => this._onAssetSelected(asset.name, asset.id, e)} >
                <span>{asset.name}</span>
            </ListItem>
        );
    })

  }
</List>
Comments