Home > Software design >  React click event not work when child element is clicked
React click event not work when child element is clicked

Time:11-03

This is my code,

export default myComponent = () => {
    const handleClick = (e) => {
        const parent = e.target.parentElement;

        if (parent.classList.contains('selected_category')) {
            parent.classList.remove('selected_category');
        } else {
            parent.classList.add('selected_category');
        }
    };

    return (
        <>
            <ul>
                <li className="">
                    <a onClick={handleClick}>
                        content<span class="text-gray-25 font-size-12 font-weight-normal">
                            121
                        </span>
                    </a>
                </li>
                <li className="">
                    <a onClick={handleClick}>
                        content<span class="text-gray-25 font-size-12 font-weight-normal">
                            121
                        </span>
                    </a>
                </li>
            </ul>
        </>
    );
}

I wrote this code for when I clicked tag element the parent element of it gets the class 'selected_category' if it doesn't already have. But the problem here is when I click children class then 'selected_category' class is added to parent tag. is there any solution to prevent it?

This is my code in </iframe>" rel="nofollow noreferrer">sand box

CodePudding user response:

To further elaborate on my comment: the issue comes from the use of e.target, which can refer to the element where the event listener is bound to OR its descendant(s). In this case, your <a> tag has <span> as a child. When a click event bubbles up to your <a> tag that originated from the inner <span>, then e.target will refer to the latter: which is not what you want.

To ensure that you get the reference to the actual element which the event listener is bound to is all times, you need to use e.currentTarget:

The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred and which may be its descendant.

Therefore your updated function should simply use currentTarget instead, i.e.:

const handleClick = (e) => {
    // NOTE: Use e.currentTarget here instead of e.target
    const parent = e.currentTarget.parentElement;

    if (parent.classList.contains('selected_category')) {
        parent.classList.remove('selected_category');
    } else {
        parent.classList.add('selected_category');
    }
};
  • Related