How do I dynamically switch between dark theme and light theme of Ant Design in a create-react-app production environment?
To be able to theme Ant Design, instead of importing Ant Design's compiled css files, you should import its less files and override the values of less variables contained within these files. You should configure your bundler for handling less files to override its variables.
On your phone, open the Settings app. Tap Display. Turn Dark theme on or off.
You can set the Spin Component Color by adapting the background-color of the ant-spin-dot-item in your component css file.
app.jsx
import { Button, Select } from 'antd';
import { ThemeProvider, useTheme } from 'antd-theme';
import React from 'react';
import ReactDOM from 'react-dom';
import { SketchPicker } from 'react-color';
const initialTheme = {
name: 'default',
variables: { 'primary-color': '#00ff00' },
};
const ThemeSelect = () => {
const [{ name, variables, themes }, setTheme] = useTheme();
return (
<>
<Select
style={{ width: 100 }}
value={name}
onChange={
(theme) => setTheme({ name: theme, variables })
}
>
{
themes.map(
({ name }) => (
<Select.Option key={name} value={name}>
{name}
</Select.Option>
)
)
}
</Select>
<SketchPicker
color={variables['primary-color']}
onChange={(value) => {
// Will update all css attributes affected by primary-color
setTheme({ name, variables: { 'primary-color': value.hex } });
}}
/>
</>
);
};
const App = () => {
const [theme, setTheme] = React.useState(initialTheme);
return (
<ThemeProvider
theme={theme}
onChange={(value) => setTheme(value)}
>
<ThemeSelect />
<Button type="primary">Button</Button>
</ThemeProvider>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
config-overrides.js
const { override, fixBabelImports, addLessLoader, addPostcssPlugins, adjustStyleLoaders, addWebpackPlugin } = require('customize-cra');
const AntdThemePlugin = require('antd-theme/plugin');
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: true,
}),
addLessLoader({
javascriptEnabled: true,
}),
adjustStyleLoaders(
(loaders) => {
loaders.use[0] = {
loader: AntdThemePlugin.loader
}
}
),
addWebpackPlugin(
new AntdThemePlugin({
themes: [
{
name: 'dark',
filename: require.resolve('antd/lib/style/themes/dark.less'),
},
{
name: 'compact',
filename: require.resolve('antd/lib/style/themes/compact.less'),
},
],
})
),
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With