0

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);    


    }
Community
  • 1
  • 1
Brian Var
  • 6,029
  • 25
  • 114
  • 212

1 Answers1

2

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>
Pranesh Ravi
  • 18,642
  • 9
  • 46
  • 70
  • Using typical closures is the way to go. I would also pass complete asset object rather than specific properties. – gor181 Sep 27 '16 at 12:11
  • So I defined an anonymous function as above. The console in dev tools tells me `Uncaught TypeError: Cannot read property '_onAssetSelected' of undefined` I can see that this method is defined in the class. Or am I missing something else here? – Brian Var Sep 27 '16 at 12:38
  • You should add `var _this = this` before the `return` in render and use `_this._onAssetSelected` inside the map. – Pranesh Ravi Sep 27 '16 at 12:45
  • Ok that works! why do I need to declare a var for _this Instead of just using .this? – Brian Var Sep 27 '16 at 13:06
  • That's because the this inside the map will have the context of the map function. But, your callback is in the React's context which is outside the map. So you need to use the exterior context to call your callback. That's why you need to copy the React's context to _this and use it inside map. I'm replying to the comment via my mobile, so, excuse the formatting. And consider approving the answer. – Pranesh Ravi Sep 27 '16 at 13:13