'Material UI IconButton onClick doesn't let to handle event

I installed "@material-ui/core": "^4.9.2" and "@material-ui/icons": "^4.9.1".

In my form i have several rows, each row has an add button and a remove button. I want the remove button to remove the row from it was clicked. It works fine with regular Button with a "-" character in it. But i want it fancy, so i replaced my Button from an IconButton, and imported the icons to use

import {AddCircleOutline,RemoveCircleOutlineOutlined} from "@material-ui/icons";

And my IconButton looks like this:

        <IconButton
          onClick={props.onRemoveClick}
          className="align-self-center"
          color="info"
          size="sm"
          disabled={props.index > 0 ? false : true}
          <RemoveCircleOutlineOutlined/>
        </IconButton>

When the IconButton is hit, the onClick method is called (i know because of logs in my console) but i can't handle the event because it is now undefined.

The funny thing is that if i click on the button area that doesn't correspond to the icon, it works. But obviously i need it to work in the whole area of the button.

enter image description here

It is not a binding issue because i already tested it.

Any ideas?



Solution 1:[1]

Well you gave an idea. Since i needed an index to identify the row's button, i sended the index through a paramater on the onClick method, like this:

onClick={e => props.onRemoveClick(props.index)}

In this way i didn't need to handle the event. I also had to bind my method on the constructor:

constructor(props) { super(props); this.handleRemoveClick = this.handleRemoveClick.bind(this); }

Now i got the behaviour wanted

Solution 2:[2]

Props that are not cited in the documentation are inherited to their internal <EnhancedButton />, so you need to use a wrapper.

      <IconButton
          onClick={(e) => props.onRemoveClick(e)}
          className="align-self-center"
          color="info"
          size="sm"
          disabled={props.index > 0 ? false : true}
          <RemoveCircleOutlineOutlined/>
        </IconButton>

Solution 3:[3]

You can see the github ussue here. There is some problem with typescript definition files but we can work around it.

Solution

I tried to solve it like in the github issue but didn't work. So this works for me.

const onClick = (e: any) => {
    // e is of type any so the compiler won't yell at you

}
<IconButton onClick={(e) => onClick(e)}>

Solution 4:[4]

I don't know the reason but using e.currentTarget helped me to get the button that I wanted and not the material icon inside it.

onClick={(e) => {
    return console.log(e.currentTarget)
}}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ricardo Álvarez
Solution 2
Solution 3 ?????????? ?.
Solution 4 Tyler2P