0

In the below code When clicked on settings the page is redirected to google.com even the e.stopPropagation is written in setting's onClick handler

    <a className="App" href="http://google.com" onClick={() => alert("parent")}>
      Home
      <div
        href={"http://youtube.com"}
        onClick={e => {
          alert("child");
          e.stopPropagation();
        }}
      >
        Settings
      </div>
    </a>

Why is that? But When I add e.preventDefault() it is not redirecting to google.com ? Why e.stopPropagation not working and e.preventDefault is working.Can anyone explain.

sandbox link - https://codesandbox.io/s/l7wx5yzp6m

Thanks.

codeGen
  • 11
  • 3
  • [This](https://stackoverflow.com/questions/24415631/reactjs-syntheticevent-stoppropagation-only-works-with-react-events) may help you. – Adrian Pop Jan 25 '19 at 18:16
  • If you don't want the page to redirect either use `e.preventDefault` or `return false;` in your function. – Adam H Jan 25 '19 at 18:17
  • Hello I tried the sandbox and I was not redirected. – AlejandroDG Jan 25 '19 at 18:18
  • @AlejandroDG please try the direct sandbox preview link https://l7wx5yzp6m.codesandbox.io/, for some reason in the sandbox preview the link is not redirecting. – codeGen Jan 25 '19 at 18:20
  • @AdamH But why `e.preventDefault()`? `e.stopPropagation` must stop the event from propagating the event from child to parent right? – codeGen Jan 25 '19 at 18:21
  • Yes, the event won't be propagated using `e.stopPropagation` but the default event for a link is to redirect to that link, so if you don't want the default action taken then you need to `e.preventDeault`. – Adam H Jan 25 '19 at 18:26
  • @AdamH Yes, that makes sense. Thanks. – codeGen Jan 25 '19 at 18:46

0 Answers0