Home > Enterprise >  NextJS onClick not working on Components?
NextJS onClick not working on Components?

Time:12-02

In my nextjs-app I have a button component

Button.tsx :

interface Button{
   text: string
   onClick?: () => void
}

const MyButton = ({ text, onClick }: Button) => {
   return (
      <button>
        {text}
      </button>
  )
}

which I call on one of my pages:

const Page= () => {

  const doStuff = () => {
    console.log('do anything')
  }

   return(
     <div>
       <Button text="Foo" onClick={dostuff}
     </div>       
   )
}

export default Page

when I click the Button, nothing happens - why is that? Did I miss something?

CodePudding user response:

Bind the click event to the button

const MyButton = ({ text, onClick }: Button) => {
   return (
      <button onClick={onClick}>
        {text}
      </button>
  )
}

And call MyButton from parent

  return(
     <div>
       <MyButton text="Foo" onClick={dostuff} />
     </div>       
   )
  • Related