Broaden your horizons with current Target.

Randy Taylor
2 min readFeb 25, 2021

Typically in JavaScript front-end development you will add event listeners to very specific targets. React is different and because you are using scripting to create your HTML there may be unexpected behavior. Let me explain.

Take a Button class component you might create in react for example. I’ve seen this commonly and is somewhat a standard and I would stay a ‘best practice’ . If I am going to have a button anywhere on my React page I’m going to create a Component to build my button. This has benefits of better styling, reusability, and separation of concerns. Like most things in React you will surround this component with surrounded <div></div>s.

Instead of adding a button directly a custom class with a div and css will give you improvement visually. However this will have unexpected behavior when adding onClick to the div. Unlike a button which is exactly one HTML element a div is a wrapper of other elements. Understandably if you add onClick to your React div you want a click to anywhere in that div to trigger it. However if you also have any other p’s, ul’s, li’s, h1's-h6's or anythine else for that matter somewhere inside that div it will change your onClick. If you read the MDN documentation(which should be your bedtime bible at this point) it basically tells you this the the thing you clicked. If you clicked the p this will be the event.target. It does not matter the onClick was attached to the div. I wrote about something related to this before here ≤ and and we can refresh. The only difference between this post and then was before we added the eventlistener to the entire page. Here we just add it to the div. The div is lisening and it DOES trigger the onClick. However e.target will be the p(or the exact element you clicked on). Unless you ONLY click on the div event.target will never be the div. You can use event.currentTarget which is the parent Element.

--

--