DEV Community

loading...
Cover image for How to stop child elements from inheriting parent element's onClick in React

How to stop child elements from inheriting parent element's onClick in React

Kunal Bagaria
Full Stack Developer
Updated on ・1 min read

So you created a div with an onClick that redirects to a link or does any normal function. But that div also contains child elements that would do different functions or nothing at all, and are still doing the parent element's function. There is a very simple solution to fix this.

Suppose this react code:

import React from 'react'

const NormalReactElement = () => {
   return (
      <div onClick={() => console.log('Parent Element!')}>
         <div id="child-element">
            <p>I am a child element</p>
         </div>
      </div>
   )
}
Enter fullscreen mode Exit fullscreen mode

So how do you fix this? Here's how you can fix this:

const NormalReactElement = () => {

   const handleChildElementClick = (e) => {
      e.stopPropagation()
      // Do other stuff here
   }

   return (
      <div onClick={() => console.log('Parent Element!')}>
         <div id="child-element" onClick={(e) => handleChildElementClick(e)}>
            <p>I am a child element</p>
         </div>
      </div>
   )
}
Enter fullscreen mode Exit fullscreen mode

Hope you like the quick solution to this, I'll see you in the next article.

Discussion (3)

Collapse
miketalbot profile image
Mike Talbot

I do this so much that I wrote this wrapper:

export function prevent(fn, defaultOnly) {
    return (e, ...params) => {
        e && e.preventDefault()
        !defaultOnly && e && e.stopPropagation()
        fn(e, ...params)
    }
}
Enter fullscreen mode Exit fullscreen mode

Then just:


import {prevent} from 'somewhere'

const NormalReactElement = () => {
   return (
      <div onClick={() => console.log('Parent Element!')}>
         <div id="child-element" onClick={prevent(()=>console.log("Child Element!"))>
            <p>I am a child element</p>
         </div>
      </div>
   )
}
Enter fullscreen mode Exit fullscreen mode
Collapse
kb24x7 profile image
Kunal Bagaria Author • Edited

I see, I didn't think about it before. Thanks for sharing :)

Collapse
owenmelbz profile image
Owen Melbourne

in javascript*