Home > other >  stopPropagation on input field inside a Link component
stopPropagation on input field inside a Link component

Time:04-08

I´m using a react router Link component and an input field inside it. how should I stop propagation?

<Link to="my-page">
    <input onm ouseDown={e => e.stopPropagation()} />
</Link>

Tried with onFocus, onClick but the Link is still triggered

CodePudding user response:

The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements. Whereas The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. In this case, we have a 'native' HTML event (or at least its emulation in JS), therefore we want to cancel the default action.

So just use e.preventDefault()

const handleClick = (e) => {
  e.preventDefault();
  return console.log("It works");
};

CodePudding user response:

Try this:

  const navigate = useNavigate();
  
  <div
    onClick={() => {
      console.log("propagated");
      navigate("/my-page");
    }}
  >
    <input type="text" onClick={(e) => e.stopPropagation()} />
  </div>;
  • Related