I am currently trying to add a Color Mode Switch to my Vite React app using Chakra UI. Unfortunately I am not able to get the desired results.
When clicking a switch to toggle the color mode it changes from light to dark mode, but if you click the switch again, it will not render in light mode.
main.tsx
const root = ReactDOM.createRoot(document.getElementById("root")!);
root.render(
<>
<ColorModeScript initialColorMode={customTheme.config.initialColorMode} />
<React.StrictMode>
<ChakraProvider
theme={customTheme}
>
<BrowserRouter>
<AuthProvider> //<- custom provider
<App />
</AuthProvider>
</BrowserRouter>
</ChakraProvider>
</React.StrictMode>
</>
);
theme.ts
import {
extendTheme,
ThemeConfig,
withDefaultColorScheme,
} from "@chakra-ui/react";
const config: ThemeConfig = {
initialColorMode: "light",
useSystemColorMode: false,
};
export const customTheme = extendTheme(
{
config,
colors: {
brand: {
50: "#FFB7B1",
100: "#FF9E98",
200: "#FF3E30",
300: "#FB1100",
400: "#C80D00",
500: "#930A00",
600: "#890900",
700: "#7F0800",
800: "#740800",
900: "#6A0700",
},
},
},
withDefaultColorScheme({ colorScheme: "brand" })
);
Settings.tsx
export const Settings = () => {
const { colorMode, toggleColorMode } = useColorMode();
const handleDarkModeChange = () => {
toggleColorMode();
};
return (
<Container marginTop={8} width="full">
<VStack spacing={6}>
<Flex width="full">
<BackButton />
<Heading flex={1}>Einstellungen</Heading>
</Flex>
<InputGroup size="lg">
<InputLeftElement pointerEvents="none">
<Icon as={MagnifyingGlass} />
</InputLeftElement>
<Input type="text" placeholder="Suche" onChange={handleSearch} />
</InputGroup>
<List width="full" spacing={6}>
<ListItem>
<InstallButton />
</ListItem>
//does not toggle correctly
<ListItem>
<FormControl
display="flex"
alignItems="center"
justifyContent="space-between"
>
<FormLabel htmlFor="dark-theme-switch" margin={0} fontSize="lg">
Dark Theme
</FormLabel>
<Switch
id="dark-theme-switch"
size="lg"
onChange={handleDarkModeChange}
/>
</FormControl>
</ListItem>
</List>
</VStack>
</Container>
);
}
Found a fix. Issue was not related to chakra-ui but my implementation handling state and rendering this state