简体   繁体   中英

How to apply antd dark theme for a React App?

I want to use this dark theme for my new react web app: https://github.com/ant-design/ant-design-dark-theme

After following directions on customizing theme here and directions on applying the theme in README here my config-overrides.js looks like this:

const { darkTheme } = require('@ant-design/dark-theme');
const { override, fixBabelImports, addLessLoader } = require('customize-cra');

module.exports = override(
  fixBabelImports('import', {
    libraryName: 'antd',
    libraryDirectory: 'es',
    style: true,
  }),
  addLessLoader({
    javascriptEnabled: true,
    modifyVars: darkTheme
  }),
);

This does not seem to be working. For example, I have a Menu antd component still showing up in "light" theme instead of "dark" theme.

I would like to have all my antd components render with the dark theme without me explicitly setting it. Is that possible? If yes, what am I doing wrong?

Not a frontend dev here, so please let me know if I am missing something obvious.

The solution that worked for me was a combination of both @JoseFelix and @Anujs answers. Thank you both for the answers:

const darkTheme = require('@ant-design/dark-theme');
const { override, fixBabelImports, addLessLoader } = require('customize-cra');

module.exports = override(
  fixBabelImports('import', {
    libraryName: 'antd',
    libraryDirectory: 'es',
    style: true,
  }),
  addLessLoader({
    javascriptEnabled: true,
    modifyVars: darkTheme.default
  }),
);

The code is destructuring the default export when the default export is the object with the variables. Therefore, it should be:

const darkTheme = require('@ant-design/dark-theme').default;
const { override, fixBabelImports, addLessLoader } = require('customize-cra');

module.exports = override(
  fixBabelImports('import', {
    libraryName: 'antd',
    libraryDirectory: 'es',
    style: true,
  }),
  addLessLoader({
    javascriptEnabled: true,
    modifyVars: darkTheme
  }),
);

If you console log darkTheme variable which has been imported, all the styling variables are present within darkTheme.default object. I have implemented their aliyum-theme .

So for you code to work, you need to change modifyVars within config-overrides.js file to

const { darkTheme } = require('@ant-design/dark-theme');
const { override, fixBabelImports, addLessLoader } = require('customize-cra');

module.exports = override(
  fixBabelImports('import', {
    libraryName: 'antd',
    libraryDirectory: 'es',
    style: true,
  }),
  addLessLoader({
    javascriptEnabled: true,
    modifyVars: {...darkTheme.default}
  }),
);

ProTip: To override darkTheme within the application, you can create your own javascript file and import it within config-overrides.js file and destructure within modifyVars

The previous answers weren't working for me. This is what worked for me if it helps anybody else. I think it's due to the new less loader version and/or a change in how antd is packaged (I am really not sure).

const { getThemeVariables } = require("antd/dist/theme");
const { override, fixBabelImports, addLessLoader } = require("customize-cra");

module.exports = override(
  fixBabelImports("import", {
    libraryName: "antd",
    libraryDirectory: "es",
    style: true,
  }),
  addLessLoader({
    lessOptions: {
      javascriptEnabled: true,
      modifyVars: {
        ...getThemeVariables({
          dark: true,
          compact: true,  // optional
        }),
      },
    },
  })
);

https://www.npmjs.com/package/antd-theme

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'));

For those who are using react-app-rewire-less and customize-cra with react-app-rewired, enable javascript like this

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'),
        },
      ],
    })
  ),
);

2023 - Ant Design V5 Suuuuuper simple implementation for anyone looking at V5.

This is NextJS not React, but you get the just:

import { ConfigProvider, theme } from 'antd';
import '../styles/globals.css';
import 'antd/dist/reset.css';

export default function App({ Component, pageProps }) {
  return (
    <ConfigProvider
      theme={{
        token: {
          // any theme overirdes
          colorPrimary: '#7f00ff',
        },
        // this line sets it to dark mode
        algorithm: theme.darkAlgorithm,
      }}
    >
      <Component {...pageProps} />
    </ConfigProvider>
  );
}

https://ant.design/docs/react/customize-theme#use-preset-algorithms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM