I am working on a Next.js application with Ant Design v5 and I'm trying to implement a dynamic theme toggle to switch between light and dark modes. I've encountered a issue: the theme settings work correctly on initial load, but subsequent changes to the isDarkMode
state don't seem to have any effect. Here's the updated part of my code in the layout.tsx
file:
"use client";
import React, { useState } from "react";
import { ConfigProvider, Layout, theme as antdTheme, Switch } from "antd";
import { Content } from "antd/es/layout/layout";
import { BulbFilled, CloudFilled } from "@ant-design/icons";
const PublicLayout = ({ children }) => {
const { defaultAlgorithm, darkAlgorithm } = antdTheme;
const [isDarkMode, setIsDarkMode] = useState(false);
const handleClick = (checked) => {
setIsDarkMode(prevValue => !prevValue);
};
return (
<ConfigProvider
theme={{
algorithm: isDarkMode ? darkAlgorithm : defaultAlgorithm,
}}
>
<Layout>
<StyledHeader>
<Switch
checkedChildren={<BulbFilled />}
unCheckedChildren={<CloudFilled />}
onChange={handleClick}
/>
</StyledHeader>
<Content>{children}</Content>
</Layout>
</ConfigProvider>
);
};
export default PublicLayout;
Initially, the theme is set based on the isDarkMode
state, but when I toggle the switch, although the isDarkMode
state changes (as I verified through console logs), the theme does not update as expected. I suspect the issue might be related to SSR and how I'm applying the theme in ConfigProvider
, or maybe something else is missing in my approach to state management and theme application.
Has anyone faced a similar issue or can identify what I might be doing wrong? Any insights or suggestions to fix this issue would be immensely helpful!
After adding package @ant-design/nextjs-registry
, it works like a charm.