43

NextJS Error Message

Error: Event handlers cannot be passed to Client Component props. ^^^^^^^^^^ If you need interactivity, consider converting part of this to a Client Component.

const reqHelp = () => {
    Swal.fire({
        title: '1',
        text: '1',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes',
        cancelButtonText: 'No',
    })
}
return(
        <div className="buttons">
            <button onClick={reqHelp} className="stopwatchButton">Request Help</button>
        </div>
);

Search NextJS 13 Official Document and about Server/Client Render

Mayank Kumar Chaudhari
  • 16,027
  • 10
  • 55
  • 122
밍원MinGWon
  • 435
  • 1
  • 4
  • 6
  • 1
    Have you tried converting that component to a client component, i.e. add `'use client';` at the top of the file? – juliomalves Nov 21 '22 at 22:30

2 Answers2

63

Add

'use client';

on top of the file where you are using handleClick because all components in Next 13 by default are server components, therefore for client side interactivity you need to use use client.

bramp
  • 9,581
  • 5
  • 40
  • 46
shivanshu
  • 654
  • 5
  • 5
  • 1
    But then you instantly run into issues because NextJS has issues rendering async components ..argggh – Spock Feb 07 '23 at 21:52
  • Yeah, you can't just use fetch in Client Components. NextJS recommends using a data-fetching library like SWR or React Query https://beta.nextjs.org/docs/data-fetching/fetching#use-in-client-components – Kedel Mihail Feb 26 '23 at 10:17
  • This seems like a backward step. I believe you could bind click handlers in server components in Next 12 (using getStaticProps). – darKnight Aug 10 '23 at 18:29
  • @darKnight previously with gsp/gssp/isr you could choose only a single hydration method for the entire route/page.tsx. now with server components you can choose hydration methods at component level without think about it at the route level. also with server components you have the ability to fallback to a loading state with suspense, but with gssp you had to wait (got white screen, even worse with cold starts, i have seen it go as high as 20 seconds) for the entire page to get server rendered. – shivanshu Aug 14 '23 at 07:35
4

Client components can be imported into server components, but not the other way around, this allows us to create server or client components at the component level.

For example let's say we have an offending piece of code like a button in an async server component that throws errors due to implementing the onClick event handler, we can extract the button into it's own client component by adding the "use client" annotation at the very first line of the new button component, that way we can still use await in the our async server component and then import the button as a client component.

Read more on composing client and server components