Created
August 7, 2022 10:35
-
-
Save tomhicks/f73708ee60cfd09bb4037842e42b9914 to your computer and use it in GitHub Desktop.
SSR colorMode in Next.js with ChakraUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {ChakraProvider, useColorMode} from "@chakra-ui/react" | |
import {Html} from "next/document" | |
import React from "react" | |
type ColorMode = "light" | "dark" | |
export function ChakraThemedHtmlComponent(props: { | |
colorMode: ColorMode | |
children: React.ReactNode | |
}) { | |
return ( | |
<Html data-theme={props.colorMode} style={{colorScheme: props.colorMode}}> | |
{props.children} | |
</Html> | |
) | |
} | |
export function ChakraThemedBodyComponent({ | |
colorMode, | |
...props | |
}: React.ComponentProps<"body"> & {colorMode: ColorMode}) { | |
return ( | |
<body | |
{...props} | |
className={ | |
props.className | |
? `${props.className} chakra-ui-${colorMode}` | |
: undefined | |
} | |
></body> | |
) | |
} | |
export function ChakraThemedProvider({ | |
colorMode, | |
...props | |
}: React.ComponentProps<typeof ChakraProvider> & {colorMode: ColorMode}) { | |
return ( | |
<ChakraProvider | |
colorModeManager={{ | |
get: () => colorMode, | |
set: () => undefined, | |
type: "cookie", | |
}} | |
theme={props.theme} | |
> | |
<EnforceColorMode desiredColorMode={colorMode} /> | |
{props.children} | |
</ChakraProvider> | |
) | |
} | |
function EnforceColorMode({desiredColorMode}: {desiredColorMode: ColorMode}) { | |
const {setColorMode} = useColorMode() | |
React.useEffect(() => { | |
setColorMode(desiredColorMode ?? "dark") | |
}, [desiredColorMode, setColorMode]) | |
return null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment