Pass value to onClick method in template in React

React boys and girls, here

                <List component="nav" aria-label="main mailbox folders">
                  {
                    this.state.apiRes.map((todo: any, i: any) =>
                      <ListItem button key={i}>
                        <ListItemIcon>
                          <InboxIcon />
                        </ListItemIcon>
                        <ListItemText primary={todo.item} />
                        <ListItemSecondaryAction>
                          <IconButton edge="end" aria-label="delete" onClick={this.handleDelete}>
                            <DeleteIcon />
                          </IconButton>
                        </ListItemSecondaryAction>
                      </ListItem>
                    )
                  }
                </List>

when the onClick= is triggered, I want to pass the todo.item to it, so as to access in

  handleDelete(value: any) {
    console.log(value);
  }

How is it done in react?

Okay, got it

                        <IconButton edge="end" aria-label="delete" onClick={(e) => {
                            e.stopPropagation();
                            e.preventDefault();
                            this.handleDelete(todo.item);
                          }}>
                            <DeleteIcon />
                          </IconButton>

You might want to remove e.stopPropagation() and pass e to this.handleDelete() so you can keep the onClick clean. Also, you don’t want to use the index as the key in the list item.

1 Like