Color Mode
Updating the theme config
1
2
3
4
5
6
7
8
9
10
11
12 | └── 📁src
└── App.css
└── App.tsx
└── 📁assets
└── logo.webp
└── react.svg
└── 📁components
└── NavBar.tsx
└── index.css
└── main.tsx
└── theme.ts
└── vite-env.d.ts
|
theme.ts |
---|
1
2
3
4
5
6
7
8
9
10
11
12
13 | // 1. import `extendTheme` function
import { extendTheme, type ThemeConfig } from "@chakra-ui/react";
// 2. Add your color mode config
const config: ThemeConfig = {
initialColorMode: "dark",
useSystemColorMode: false,
};
// 3. extend the theme
const theme = extendTheme({ config });
export default theme;
|
Remember to pass your custom theme
to the ChakraProvider
, otherwise your color mode config won't be taken into consideration.
main.ts |
---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 | import React from "react";
import ReactDOM from "react-dom/client";
import { ChakraProvider, ColorModeScript } from "@chakra-ui/react";
import App from "./App";
import "./index.css";
import theme from "./theme";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<ChakraProvider theme={theme}>
<ColorModeScript initialColorMode={theme.config.initialColorMode} />
<App />
</ChakraProvider>
</React.StrictMode>
);
|
Building the Color Mode Switch
1
2
3
4
5
6
7
8
9
10
11
12
13 | └── 📁src
└── App.css
└── App.tsx
└── 📁assets
└── logo.webp
└── react.svg
└── 📁components
└── ColorModeSwitch.tsx
└── NavBar.tsx
└── index.css
└── main.tsx
└── theme.ts
└── vite-env.d.ts
|
ColorModeSwitcher.tsx |
---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 | import { HStack, Switch, Text, useColorMode } from "@chakra-ui/react";
const ColorModeSwitch = () => {
const { toggleColorMode, colorMode } = useColorMode();
return (
<HStack>
<Switch
colorScheme="green"
isChecked={colorMode === "dark"}
onChange={toggleColorMode}
/>
<Text>Dark Mode</Text>
</HStack>
);
};
export default ColorModeSwitch;
|
NavBar.tsx |
---|
1
2
3
4
5
6
7
8
9
10
11
12
13 | import { HStack, Image } from "@chakra-ui/react";
import logo from "../assets/logo.webp";
import ColorModeSwitch from "./ColorModeSwitch";
const NavBar = () => {
return (
<HStack justifyContent="space-between" padding="10px">
<Image src={logo} boxSize="60px" />
<ColorModeSwitch />
</HStack>
);
};
export default NavBar;
|
2024-07-12 23:20 2024-07-13 14:51