Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put an onClick event on an font awesome icon in react?

I am trying to set an onClick event on a fontawesome icon but it doesnt work when I do this.

 <i class="fab fa-accessible-icon" onClick={this.removeItems}></i>

It only works when I put the onClick on p tags or h tags like this.

 <h1 onClick={this.removeItems}><i class="fab fa-accessible-icon"></i></h1>

It is not possible to set event on icon itself? Doing this the second way is causing me style errors.

Edit: I did change the class to className, my bad. but its still not working and currently im bypassing it using around the icon and having the onClick on the span.

like image 456
craftdeer Avatar asked Mar 23 '18 05:03

craftdeer


People also ask

Can you use onClick in react?

The React onClick event handler enables you to call a function and trigger an action when a user clicks an element, such as a button, in your app. Event names are written in camelCase, so the onclick event is written as onClick in a React app. In addition, React event handlers appear inside curly braces.


1 Answers

Well it should work like below...

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<i class="fa fa-cog" onClick="console.log('Clicked')"></i>

If its not try to wrap your icon into a button

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<button><i class="fa fa-cog" onClick="console.log('Clicked')"></i></button>
like image 51
Bhuwan Avatar answered Sep 19 '22 13:09

Bhuwan