-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathStyledThemeProvider.js
More file actions
41 lines (34 loc) · 1.22 KB
/
StyledThemeProvider.js
File metadata and controls
41 lines (34 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//uses isDark state to choose styled-component theme (in themeStyles.js)
//and use ThemeProvider to allow all styled components access to values via props.theme
import React, { useContext } from "react";
import { ThemeProvider } from "styled-components";
import { ThemeManagerContext } from "./ThemeManager";
// Safe check for browser environment
const isBrowser = typeof window !== "undefined";
export const StyledThemeProvider = (props) => {
const { children, darkTheme, lightTheme } = props;
const { isDark, didLoad } = useContext(ThemeManagerContext);
// For SSR, we need to provide a consistent theme initially
// This ensures the server and client render the same thing initially
const currentTheme = isDark ? darkTheme : lightTheme;
const theme = {
...(didLoad ? currentTheme : transformTheme(currentTheme)),
};
return (
<ThemeProvider theme={theme}>
<>{children}</>
</ThemeProvider>
);
};
const transformTheme = (theme) => {
const newTheme = {};
Object.keys(theme).forEach((key) => {
const value = theme[key];
if (typeof value === "object" && !!value) {
newTheme[key] = transformTheme(value);
} else {
newTheme[key] = `var(--${key})`;
}
});
return newTheme;
};