'Set theme on server before sending to browser
I'm using Nextjs and Material UI. I want to change the theme based on the hostname(different clients will have different hostnames and different themes).
I did something like dynamically import theme file inside useEffect, but that briefly shows the default theme and then changes the colours after import is done.
I want to render the html with the respective theme for the client on the server itself. What I've done below works(I saw the network tab preview of html with respective theme applied), but don't know how it works since I am setting theme in useState(createTheme(themeObj))
This is theme/index.ts:
import defaultTheme from './default.theme';
import org1Theme from './org1.theme';
const allThemes = {
org1: org1Theme,
default: defaultTheme,
};
export default allThemes;
In _app.ts I import allThemes and use getInitialProps to get the theme object from allThemes based on hostname and send it to MyApp component as props.
_app.tsx:
MyApp.getInitialProps = async (appContext: AppContext) => {
const [hostName] = appContext.ctx.req?.headers.host?.split(':') || [''];
let themeKey = 'default';
if (hostName === 'org1.com') themeKey = 'org1';
return {
...appProps,
themeObj: allThemes[themeKey],
};
};
The MyApp component in _app.tsx:
import allThemes from '../theme';
function MyApp({themeObj}: AppProps) {
const [theme] = useState(createTheme(themeObj)); //themeObj from props from getInitialProps
return (
<CacheProvider value={emotionCache}>
<ThemeProvider theme={theme}>
...
My question is, is this the right way to do what I'm trying to achieve and don't understand how useState(createTheme(themeObj)) works(I saw the network tab preview with respective theme applied) since useState is executed on client side(right?). I'm new to nextjs(react too, kind of) and don't know if something might break because I don't fully understand client/server side rendering.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
