Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable to onClick in React [duplicate]

I am developing my UI using React and (for now at least) using Material-UI, which has and tags. Inside ListItem, I want to detect a click on an icon. The issue is my list will have a number of listitems, and I want to pass the index of the listite into my click handler. But I also need to pass in the click event itself. My code looks like this:

class SomeList extends React.Component { 

    handleClickDeleteIcon(e) {
        e.stopPropagation();
        console.log('Fired handleClickDeleteIcon()!');
    }

    everywhereClickFunction(e) {
        console.log('Fired everywhereClickFunction()!');
    }

    render() {
        return (
            <List>
              <Subheader inset={true}>Some Files</Subheader>
              <ListItem
                leftAvatar={<Avatar icon={<ActionAssignment />} backgroundColor={blue500} />}
                rightIcon={
                    <div onClick={this.handleClickDeleteIcon}>
                        <DeleteForever />
                    </div>
                }
                primaryText="Vacation itinerary"
                secondaryText="Jan 20, 2014"
                onTouchTap={this.everywhereClickFunction}
                onClick={this.everywhereClickFunction}
              />
              <ListItem
                leftAvatar={<Avatar icon={<ActionAssignment />} backgroundColor={blue500} />}
                rightIcon={
                    <div onClick={this.handleClickDeleteIcon}>
                        <DeleteForever />
                    </div>
                }
                primaryText="Kitchen remodel"
                secondaryText="Jan 10, 2014"
              />
              <ListItem
                leftAvatar={<Avatar icon={<ActionAssignment />} backgroundColor={blue500} />}
                rightIcon={
                    <div onClick={this.handleClickDeleteIcon}>
                        <DeleteForever />
                    </div>
                }
                primaryText="Something else"
                secondaryText="Nov 08, 2017"
              />
            </List>
        );
    }
);

So how can I use onClick for each rightIcon to pass in a variable (like a list index or some unique id) that I can use inside handleClickDeleteIcon(e)? Note that I need handleClickDeleteIcon to also get the event e so I cant call e.stopPropagation().

like image 339
Marc Avatar asked Dec 05 '25 07:12

Marc


1 Answers

You can create an anonymous function and call your function with params, like this:

<div onClick={e => this.handleClickDeleteIcon(e, index)}>
  <DeleteForever />
</div>
like image 143
Brian Genisio Avatar answered Dec 07 '25 19:12

Brian Genisio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!