Next.js Discord

Discord Forum

Opening a modal from a server component (main page)

Answered
Golden paper wasp posted this in #help-forum
Open in Discord
Avatar
Golden paper waspOP
Hi all,

I'm a bit stuck on how to open a modal from a server component. I know the easiest way is to just paste 'use client'; on top of the page and use useState from react. Now I think it is not the best option to make your main page.tsx use client so my question is, did someone work out a fancy way to make it work?

The 'problem'
I want to open a modal on the main page. This needs a state, isOpen and setIsOpen. This is needed to handle the open and close of the modal.

The dirty workaround
What I now did is setting a param in the url (?modal=true) and look for it. With the <Link> magic I then open it the modal. With again the <Link> magic I navigate back to "/" so the modal is being closed.

<div> <button className="rounded bg-custom-blue font-light p-2 w-full "> <Link href="/?modal=true">Add Data</Link> </button> { showModal && <AddDataModal />} </div>


It looks and smells fishy. Does anyone have a better option for me>?
Answered by fuma thinks joulev is rational
And then put your client component in the main page, everything works
View full answer

7 Replies

Avatar
fuma thinks joulev is rational
Why are you doing this? You can make a client component like <AddDataModalTrigger />, and just do what you used to do
You can't make pages a client component, but you can create a client component at any position or directory
Avatar
Golden paper waspOP
But when I want to have the modal on the main page that is not possible? I mean, after clicking a button show the modal. But that needs a state because otherwise the modal will always be visible.
Avatar
fuma thinks joulev is rational
what? You can just create another client component wrapping your modal
Avatar
fuma thinks joulev is rational
And then put your client component in the main page, everything works
Answer
Avatar
Golden paper waspOP
Ok, you probably think this guy is an idiot. But thanks for the comments because I fixed it now. Thanks 🙂
Avatar
fuma thinks joulev is rational
Don't worry, everyone is same when started to learn Next.js :yay: