Search code examples
javascriptreactjsonclickevent-handlingparent-child

Child triggers the onClick event of its parent


I have a parent, div, on which I've set an onClick event handler, but it is trigerred by its childrens. All I want to do is to filter one child of the parent element when the parent is clicked. I will do a list o multiple choices, using states, so that's why I need it.

Here's my code:

import { useState, useEffect } from "react";
import events from "../utils/events.js";

import "../styles/events.scss";

const Events = () => {
  const [selectedEvent, setSelectedEvent] = useState(events[0].id);

  return (
    <div className="events-container">
      <div className="events">
        <div className="events-cards">
          {events.map((event) => (
            <div
              key={event.id}
              className="event"
              onClick={(e) => {
                const date = e.target.querySelector(".date");
                date.classList.add("selected-event");
              }}
            >
              <p className="date">{event.date}</p>
              <h1 className="name">{event.name}</h1>
              <p className="description">{event.description}</p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default Events;

Solution

  • you can use the stopPropagation() method on the event object. This will stop the event from bubbling up the DOM tree and prevent it from reaching the parent element.

    onClick={(e) => {
                // Stop the click event from reaching the parent div
                e.stopPropagation();
    
                const date = e.currentTarget.querySelector(".date");
                date.classList.add("selected-event");
              }}