Winten
Winten

Reputation: 664

React how to ignore onClick for child element

I have a child component inside a parent component. I want to to alert message when I click everywhere inside parent except when clicking on child.

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    }
  }

  render() {
    return (
      <div className="parent" onClick={() => alert('x')}>
        <p>Alert clicks anywhere on this div</p>
        <div className="children">
          <button>Do not alert On this element click</button>
        </div>
        <p>Alert clicks anywhere on this div</p>
      </div>
    )
  }
}

Code example here:

http://jsfiddle.net/rgL5f9yh/

Upvotes: 6

Views: 7808

Answers (3)

Muhammad Haseeb
Muhammad Haseeb

Reputation: 1341

You can prevent event propagation in the child element i.e

<button onClick={((e) => e.stopPropagation())}>
    Do not alert On this element click
 </button>

Upvotes: 7

airtonix
airtonix

Reputation: 5164

better way is to setup a ref and only respond to clicks on that element.

export function Blanket({
  children,
  onClick,
}: PropsWithChildren<{ onClick?: () => void; }>) {
  const blanketRef = createRef<HTMLDivElement>();

  const handleCloseClick: MouseEventHandler<HTMLDivElement> = (event) => {
    if (typeof onClick !== "function") return;

    // begin type narrowing
    if (event.target !== blanketRef.current) return;

    event.stopPropagation();
    onClick();
  };

  return (
    <div
      ref={blanketRef}
      style={{
         width: '100%'
         zIndex: 1000,
         display: 'flex',
         flexDirection: 'column',
         alignItems: 'center',
         justifyContent: 'center',
         position: 'fixed',
         top: 0,
         bottom: 0,
         left: 0,
         right: 0,
         background: '#00000033'
      }}
      onClick={handleCloseClick}
    >
      {children}
    </div>
  );
}

Upvotes: 2

Nayan shah
Nayan shah

Reputation: 551

Add e.stopPropagation() to child onClick property

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    }
  }

  render() {
    return (
      <div className="parent" onClick={() => alert('x')}>
        <p>Alert clicks anywhere on this div</p>
        <div onClick={(e) => e.stopPropagation()} className="children">
          <button>Do not alert On this element click</button>
        </div>
        <p>Alert clicks anywhere on this div</p>
      </div>
    )
  }
}

Upvotes: 18

Related Questions