Next.js Discord

Discord Forum

Link and child component onClick events

Answered
Rufous-capped Warbler posted this in #help-forum
Open in Discord
Rufous-capped WarblerOP
I have a <Link> tag around a component, and a child component has an item with an onClick. When I click the child component, both the onClick and the Link tag activate. How do I have it limit which component's click event actually fires off, and prevent the other one?
Answered by Jboncz
export default function Home() {

  const gotoPagea = () => {
    console.log('page a')
  }
  const gotoPageb = (e: any) => {
    e.preventDefault();
    e.stopPropagation();
    console.log('page b')
  }
  return (
    <>
      <div onClick={() => gotoPagea()}>
        Info stuff
        <div onClick={(e) => gotoPageb(e)}>Edit</div>
      </div>

    </>
  );
}
View full answer

12 Replies

Can you show me the component?
Rufous-capped WarblerOP
It's basically <Link><div><div onClick() /><div onClick() /></div></Link
the whole box is a link, and the edit/detach icons are onClicks
Gotcha gemme a few mins
export default function Home() {

  const gotoPagea = () => {
    console.log('page a')
  }
  const gotoPageb = (e: any) => {
    e.preventDefault();
    e.stopPropagation();
    console.log('page b')
  }
  return (
    <>
      <div onClick={() => gotoPagea()}>
        Info stuff
        <div onClick={(e) => gotoPageb(e)}>Edit</div>
      </div>

    </>
  );
}
Answer
That should do it?
Rufous-capped WarblerOP
omg it really was that easy. thanks so much
np
dont forget to mark answer so it closes the thread! GL
Rufous-capped WarblerOP
didn't even think to look at the event param
Its a common thing, its called bubbling