Color Mode - animesh0701/anime-hub GitHub Wiki
It's always best to check out Chakra UI docs for color modes and how they are locally stored or in cookies. Color Mode.
Created a new theme.ts file in the src
import { extendTheme,ThemeConfig } from "@chakra-ui/react";
const config: ThemeConfig = {
initialColorMode: 'dark' //setting the initial color mode to dark
};
const theme = extendTheme({ config}); //creating a theme object that extends it with current configuration
export default theme;After this update the chakra provider as well
import { ChakraProvider, ColorModeScript } from "@chakra-ui/react";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<ChakraProvider theme={theme}>
<ColorModeScript initialColorMode={theme.config.initialColorMode} />
<App />
</ChakraProvider>
</React.StrictMode>
);Now you can delete the default light mode from local storage in the application tab.
Now to toggle between dark and light mode create a new component that will be placed in the navbar that updates the state of the color mode every time it's clicked. Here the custom hook provided by chakra can be used called useColorMode().
import React from "react";
import { HStack, Switch, Text, useColorMode } from "@chakra-ui/react"; //using a custom defined chakra hook
const ColorModeSwitch = () => {
const { toggleColorMode, colorMode } = useColorMode();
return (
<div>
<HStack>
<Switch
colorScheme="green"
isChecked={colorMode === "dark"}
onChange={toggleColorMode}
/>
<Text>Dark Mode</Text>
</HStack>
</div>
);
};
export default ColorModeSwitch;Now we add this component in the navbar
const NavBar = () => {
return (
<HStack paddingLeft="20px" pr={10} h={140} justifyContent={"space-between"}>
<HStack>
<Image src={luffy} boxSize={["60px", "80px", "100px"]}></Image>
<Text>ANIMEHUB</Text>
</HStack>
<HStack>
<ColorModeSwitch />
<SearchBar />
</HStack>
</HStack>
);
};