Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
React click event not work when child element is clicked

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 sand box

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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');
    }
};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda