Dom
Dom

Reputation: 3444

In React, a <button> with icon does not trigger function

I use reactstrap. I have this kind of <button> with an icon inside :

{this.props.mode === "update" 
  ? 
     <Button 
        className="btn btn-danger btn-sm" 
        onClick={() => this.deleteQuestion()}
     >
       <i className="fa fa-trash"></i>  
     </Button> 
  : null 
}

If I click on the icon, the function in not triggered.
If I click outside the icon (but inside the button), the function is triggered.

What is this mystery? I am a beginner in React and react-strap.

Upvotes: 0

Views: 1911

Answers (2)

Max Gram
Max Gram

Reputation: 695

The reason it behaves this way is because icon captures click before it is propagated to the button. The easiest way to fix this is to add the following in your css

.btn i.fa{
  pointer-events: 'none';
}

it will fix it for all the buttons in your project

Upvotes: 2

Anglesvar
Anglesvar

Reputation: 1154

There is a concept called event capturing and event bubbling in JavaScript. Take a look at Event Capturing and Event Bubbling. This concept helps you overcome the problem that you're facing currently.Take a look at this. You can add the same function onClick to the icon too. This will help you as well!!.. There are so many design templates available you can try those too. For eg. There's Ant Design. Hope it helps!!.. Happy Coding!!

Upvotes: 1

Related Questions