Home > OS >  Why aren't I able to use onClick with an icon using React?
Why aren't I able to use onClick with an icon using React?

Time:04-17

I am using react JS and I want to make use of an icon to basically make it look like a dropdown. Screenshot attached to this question. I am able to call an onClick function using a button but the same code is not working with an i tag. The tutorial I am following may have been outdated. But I want to know the alternative. Here is my class component. enter image description here

import React, { Component } from 'react';

import PropTypes from 'prop-types';
class Contact extends Component {
    state = {}
    onShowClick = (name, e) => {
        console.log(name);
    };
    render() {
        const { name, email, phone } = this.props;
        return (
            <div className='card card-body mb-3'>
                <h4>{name}{' '} <i onClick={this.onShowClick.bind(this, name)} className='fas fa-sort-down' /></h4>
                <button onClick={this.onShowClick.bind(this, name)}>Button</button>
                <ul className='list-group'>
                    <li className='list-group-item'>E-mail: {email}</li>
                    <li className='list-group-item'>Phone: {phone}</li>
                </ul>
            </div>
        );
    }
}
// PropTypes - TypeChecking
Contact.propTypes = {
    name: PropTypes.string.isRequired,
    email: PropTypes.string.isRequired,
    phone: PropTypes.string.isRequired
}
export default Contact;

My problem is with the tag inside the h4 tag. The function onShowClick works perfectly fine with the button but not the icon. I have used .bind and all and yet, I see no results. How do I get it working?

Thanks for the help.

CodePudding user response:

Top of my head, without reproducible minimal project, I am thinking of a couple reasons why this wouldn't be working main one being the following:

HTML is not handling your onClick properly because it is wrapped in a h4 and applied on a i tag. I strongly recommend avoiding adding the click events on h and I tags. What you could do here is have a wrapper div, get your h4 inline with your i tag, and wrap the latter with an other div onto which you apply your onClick.

CodePudding user response:

Your code should work but you have to realize that the i element is not a button. This element shouldn't handle click events for multiple reasons like keyboard navigation, and ATs. A better practice would be to wrap this icon with a button. You can also reset the css of the button.

<button
  style={{
     border: "none",
     margin: 0,
     padding: 0,
     background: "none"
  }}
  onClick={this.onShowClick.bind(this, name)}
>
   <i className="fas fa-sort-down" />
</button>
  • Related