Skip to content Skip to sidebar Skip to footer

How To Customize Antd Theme On Runtime?

I have been working with antd for quite sometime now. So far in my react app I have customized antd theme in webpack configuration and have updated default less variables. Or If I

Solution 1:

$ npm install --save antd-theme

app.jsx

import { Button, Select } from'antd';
import { ThemeProvider, useTheme } from'antd-theme';
importReactfrom'react';
importReactDOM from'react-dom';
import { SketchPicker } from'react-color';

const initialTheme = {
  name: 'default',
  variables: { 'primary-color': '#00ff00' },
};

constThemeSelect = () => {
  const [{ name, variables, themes }, setTheme] = useTheme();

  return (
    <><Selectstyle={{width:100 }}
        value={name}onChange={
          (theme) => setTheme({ name: theme, variables })
        }
      >
        {
          themes.map(
            ({ name }) => (
              <Select.Optionkey={name}value={name}>
                {name}
              </Select.Option>
            )
          )
        }
      </Select><SketchPickercolor={variables['primary-color']}
        onChange={(value) => {
          // Will update all css attributes affected by primary-color
          setTheme({ name, variables: { 'primary-color': value.hex } });
        }}
      />
    </>
  );
};

constApp = () => {
  const [theme, setTheme] = React.useState(initialTheme);
  return (
    <ThemeProvidertheme={theme}onChange={(value) => setTheme(value)}
    >
      <ThemeSelect /><Buttontype="primary">Button</Button></ThemeProvider>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));

config-overrides.js

const { override, fixBabelImports, addLessLoader, addPostcssPlugins, adjustStyleLoaders, addWebpackPlugin } = require('customize-cra');

constAntdThemePlugin = 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(
    newAntdThemePlugin({
      variables: ['primary-color'],
      themes: [
        {
          name: 'dark',
          filename: require.resolve('antd/lib/style/themes/dark.less'),
        },
        {
          name: 'compact',
          filename: require.resolve('antd/lib/style/themes/compact.less'),
        },
      ],
    })
  ),
);

Post a Comment for "How To Customize Antd Theme On Runtime?"