So I have a variable in localStorage that is changed upon using a toggle button. When I click the toggle button it correctly changes the color. However, upon refreshing the page it does not respect the color in local storage.
I'm even logging the variable and it's the correct variable - it's just not respecting it in CSS for some reason. Here's the code:
export const Home: React.VFC<any> = () => {
const theme = useRecoilValue<any>(themeAtom); // gets theme value from the store, which is synced with a localstorage effect
console.log('theme context from home: ', theme) // dark
return (
<>
<div
className={`fixed top-0 left-0 h-full w-1/2 bg-${
theme === 'dark' ? 'black' : 'white' // renders as white
}
`}
/>
...
The strange thing is, this technique is working for different contexts, like the user context or authentication context. However, specifically for CSS this is not working.
Because of how the TailwindCSS JIT engine works, if you're using bg-${/* ... */}, TailwindCSS will not detect that class and won't include it in your final build. Documentation
Instead, include bg in your ternary so Tailwind can detect the class and add it.
<div
className={`fixed top-0 left-0 h-full w-1/2 ${
theme === 'dark' ? 'bg-black' : 'bg-white'
}
`}
/>
I am facing the same issue. Think local-storage is not available in server side and thus not rendering the HTML correctly, what is frustrating that at client side, variables resolved correctly but somehow its not updating/hydrating the html.