Next.js Discord

Discord Forum

Setting global header text color based on page data

Unanswered
Orinoco Crocodile posted this in #help-forum
Open in Discord
Avatar
Orinoco CrocodileOP
I have a header (client) component which is being rendered inside the root layout.tsx file. In my routes i fetch data from Sanity, including page modules (like a page builder). The first module is a hero and has information which tells the header if it should have white or black text, based on the background of the hero. I have no way of knowing what the header should look like before the data is fetched in page.tsx in the various routes. Using context to set the value or setting a data attribute in a client component inside page.tsx doesn't work as it's not synchronous and ends up "flashing". I there a way that I "give" the header component this information synchronously, or is the a better approach to the issue?

2 Replies

Avatar
Harrier
Well, most of web is asynchronous in general. From how I understand it is that:
1. the page.tsx fetches some data,
2. the fetched data contains info about the color of the navbar

If above is true, then do the fetch as usual, and pass the color info to client component, from where you can change the color through context with use of useEffect.

I don't know exactly what you mean by "flashing", but have you looked into color transitions (CSS)?
Avatar
Orinoco CrocodileOP
Thank you for replying! The steps are correct, but I see now that "flashing" might be the wrong word. The solution using context is one that I've tried. The issue is that from the page loads it takes up to a second for the color the actually change. So if the default text color is black, and the hero tells the header it needs to be white, is will change some time after the page is loaded, leading to the text color change being visible for the user. Sadly color transitions won't solve the issue as it will still be transition after the page has loaded. I've only tested in dev mode, and it might be different in production. I'll try to build to the project and see if that helps. I'm used to PHP, so the asynchronous concepts in Next.js isn't really intuitive to me when it comes to rendering a webpage.