Next.js Discord

Discord Forum

Set background-color of body element on specific page

Unanswered
Barbary Lion posted this in #help-forum
Open in Discord
Avatar
Barbary LionOP
I have a page app/foo/[id].tsx. On that page, the background-color of the body element should be a specific color, different from the rest of the site.

I see the body element is in app/layout.tsx, and according to the docs, that's the only place that body is specified, and this component has no access to which page is being rendered. Is there another way to do this?

18 Replies

Avatar
() => "anay-208"
create a div with width 100vw and height 100vh and apply to that. There is no other way
Avatar
Barbary LionOP
Really?! Wow
Avatar
Plott Hound
you could do it with useContext but it would be a bit messy
Avatar
Barbary LionOP
That's not equivalent - one UI difference is that "scroll bounce" when scrolling up to the top of the page will still show the default body background-color
I don't mind messy, at the moment I just want possible 😄
I'm not sure how I would do this with useContext - which context? Like is there a hidden context that I can use from app/layout to discover which page I'm on
Avatar
Plott Hound
actually you wouldnt need context
take this pattern:
Image
i imagine if you made a component that only has <body>{children}</body> then you could essentially perform client side rendering to the body tag (i havent tested this)
then you could usePathname to check if you are on app/foo/[id].tsx and apply classes based on that
should work but i havent tested it
let me know how you get on
but yeah this is bad practice generally but might work
Avatar
Barbary LionOP
Oh interesting, I'll look into this - thanks!
Currently my only other plan is useEffect from the page to set style/class on the body el, and unset it after unmount
Avatar
Plott Hound
here's an example that i did and it works. just not on the body tag. i made a client wrapper in my layout so i can change classes based on a context, only difference you would be using pathname instead of context
Image
Image
that would work, either way since you are applying things fron client rendered components there might be a flash when the page loads
alternatively the thing that dictates the 'scroll bounce' colour is actually a metadata property themeColour so you could look into manipulating that too