#Context API in Next.js

39 messages · Page 1 of 1 (latest)

pearl dragon
#

I want to pass a context which I want to be available to the body of my page. How do I acheive that? Do I directly wrap the body tag instead of the children in layout.tsx? How then would I use it on the body

sick flintBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

earnest kettle
#

Then you can just use the hook inside the children of the body

pearl dragon
earnest kettle
#

What are you trying to do

pearl dragon
eager prairie
#

Why to use context if you will not use it elsewhere ?🤔

earnest kettle
#

Speaking of themes, check out next-themes

#

It handles fouc for you

pearl dragon
pearl dragon
earnest kettle
#

like if you need to do it on button click,
then just onClick={()=>document.body.style.background = "Red"}

pearl dragon
# earnest kettle like if you need to do it on button click, then just `onClick={()=>document.body...

Ok but this wouldn't work because I have to keep track of the themes so the other parts will change along with it. Currently I'm using numbers to keep track of the themes. The numbers change on toggle. I gave up on surrounding the body tho but now I'm having an issue. It says useTheme is not a function. BTW, useTheme is the custom function I created that just returns the useContext(Them context)

#

I have no idea what I'm doing wrong. Sorry it isn't clear tho

earnest kettle
#

No offense but its a bit hard to set themes correctly without fouc

#

UseTheme is not a function because useTheme is declared in the client comps

pearl dragon
earnest kettle
#

fouc is flash of unstyled content

#

okay lets do it yourself and see if you can do it

#

basically, your export default function Home is by default a server component
And you can't use client-side hooks in server component

#

so you have to create a client component by writing "use client" and exporting it

#

the client component can have useContext() to consume your theme provider

pearl dragon
#

Apparently that wasn't enough

#

I had to use use client in my layout.tsx too and page.tsx too

#

Doesn't feel right

pearl dragon
#

Looks like that solved my theme issue tho but maybe layout page client feels buggy

earnest kettle
#

it feels right to me 😭

#

if you dont want to use client

#

then use CSS to control the display of your themes

#

that way it can be server rendered

#

of course there are still cases where you need to show component, outside of the CSS ability