DEV Community

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

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
 
kunal profile image
Kunal Bagaria • Edited

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

Collapse
 
realadamsmith profile image
Adam

Would this work if you need to pass another prop to 'prevent' function and you caant pass e?

Collapse
 
miketalbot profile image
Mike Talbot ⭐

It works for any number of properties to the event handler yes. The spread params take care of that. Events always have e as the first parameter, you'd need a rewrite if this wasn't a standard event I guess.

Thread Thread
 
realadamsmith profile image
Adam

I needed to pass a prop from a child element that wasnt (e), so I just remade the whole thing so the child wouldnt be dependednt on the parent element in the meantime

I gotta study this wrapper hmm