Next.js Discord

Discord Forum

Add event handler to the button

Unanswered
Asiatic Lion posted this in #help-forum
Open in Discord
Avatar
Asiatic LionOP
Hi, everyone. I encountered a difficulty while developing web with Next.js v14. The main goal is to add onClick even handler to the button.
When I just added onClick event handler to the button, it complained that I couldn't add event handler on server component. so I searched about it on Google, and found a way to use 'use client' to make the component to server component. but it also failed with some errors, I haven't tried to find the solution of it yet.
Is there any approach or tricky which adds even handler to the button on the server component?
Any thoughts are welcome.
Thank you

11 Replies

Avatar
Chow Chow
what should the onClick you want to add do?
Avatar
Asiatic LionOP
It will have two functionalities. One is to redirect and the other one is to open modal.
Avatar
Chow Chow
redirect you can handle with the Link component instead of generic button that works server side as well and also has all the accessibility features that a link should have
Avatar
Asiatic LionOP
Ahh~ one more problem is I must use custom component which is already built for this button. so I can't replace it to Link component.
Avatar
Chow Chow
for the modal you need a client component since that's a client interaction
you can wrap your component with Link
Avatar
Asiatic LionOP
Thanks for your help. I already found it on the Google, one quick Q. is this an ideal approach?
and if I need to send api request, not open a modal, how to handle this?
Avatar
Chow Chow
you can style the Link component with css/tailwind but if that's not enough then wrapping it is fine
and for api request you can either use server action which is an async function that you mark with "use server" and then call from your client component or you can make a api route handler and call it from FE with normal fetch
Avatar
Asiatic LionOP
Really sorry to ask too much, could you provide me example code related to async function? I thought about it but couldn't get any picture of it.