Ilja Ilja - 1 month ago 8
React JSX Question

Don't trigger onClick for nested child elements

I have a simple modal component:

function Modal(props) {
return (
<div className={cx(styles.overlay, { show: props.show })} onClick={props.onClose}>
<div className={styles.modal}>
<span className={styles.closeBtn} onClick={props.onClose} />
{props.children}
</div>
</div>
)
}


the onClose prop triggers closing the modal, hence I attach it to
styles.overlay
(dark overlay that you typically see on modals that when clicked dissmises it) and to
styles.closeBtn
(a close button for modal).

The whole flow works besides the fact that anything inside
styles.overlay
when clicked on also dismisses the modal, which is not functionality I was after, hence I need to only dismiss it if that specific element is clicked not its children.

Answer
function Modal(props) {
   return (
     <div className={cx(styles.overlay, { show: props.show })} onClick= {props.onClose}>
       <div className={styles.modal} onClick={e => e.preventDefault()}>
         <span className={styles.closeBtn} onClick={props.onClose} />
         {props.children}
       </div>
   </div>
   )
}

I think, the best way is to have your overlay and your modal in two separate div, but this should work.

Comments