How to get id of the parent element in the event handler

I wrote this code

      <article key={meal.id -> Belt.Int.toString} id={meal.id -> Belt.Int.toString} className="single-meal">
        <img src={meal.thumbnail} className="img" onClick={handleClick} />
        <footer>
          <h5>{meal.mealName -> React.string}</h5>
          <button className="like-btn"><BsHandThumbsUpFill /></button>
        </footer>
      </article>

When I click the image the event handler handleClick fires and there I can get the img element by doing ReactEvent.Mouse.currentTarget(event) but how can I get the parent element because the id of the image being clicked is defined on the parent element.

I can make my code work by moving the onClick event to the article. but the problem is that when I click on button, the event handler of the button doesn’t fire. it only fires the event handler defined on the article.

You could extend the handleClick function:

let handleClick = (id, evt) => { ... }
<img src={meal.thumbnail} className="img" onClick={handleClick(meal.id)} />

On the other hand, if you have nested clickable elements, use the inner onClick event to stop the propagation.

let onButtonClick = evt => {
  evt->ReactEvent.Mouse.stopPropagation
  ...
}
1 Like