3 min read · Apr 8, 2018

Ant Design , Live Theme

If you are using Ant Design and want to update color related theme of your web app or want to use less for your custom styles then you are on right page.

In my use case, I was using Ant Design. I wanted to save color configurations mainly @primary-color and @text-color and don’t want to deploy whole new static build on AWS S3 for each different customer/tenant with his custom color settings. So updating colors at runtime using lessjs is a better solution but instead of loading all styles (including Ant Design styles and custom styles) what we can do is extract color related css using postcss plugin and replace colors with respective variable names like @primary-color and load this as less file.

.logo { width: 120px; height: 31px; color: #00375b; float: left; } // will be reduced to .logo { color: #00375b; } // Same goes for all styles

So now with any means we can run less.modifyVars() to override the styles.

yarn add react-app-rewire-antd-theme
const path = require('path'); const { updateConfig } = require('react-app-rewire-antd-theme'); const options = { varFile: path.join(__dirname, './src/styles/variables.less'), stylesDir: path.join(__dirname, './src/styles'), antDir: path.join(__dirname, './node_modules/antd'), colorFilePath: path.join(__dirname, './public/color.less'), themeVariables: [ '@primary-color', '@secondary-color', '@text-color-secondary', '@text-color', ], }; module.exports = function override(config, env) { config = updateConfig(config, env, options); return config; };
<div id="root"></div> <link rel="stylesheet/less" type="text/css" href="color.less" /> <script> window.less = { async: true, env: 'production', }; </script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/less.js/2.7.2/less.min.js" ></script>
import React from 'react'; import { Row, Col, Input, Button } from 'antd'; class ColorInput extends React.Component { state = { vars: { '@primary-color': '#dddddd' } }; onChange = (e) => { const color = e.target.value; if (color.match(/^#[a-f0-9]{3,6}$/i)) { const vars = this.state.vars; vars['@primary-color'] = color; this.setState({ vars }); } }; updateVars = () => { window.less.modifyVars(this.state.vars).then(() => { console.log('Theme updated successfully'); }); }; render() { return ( <Row> <Col xs={16}> Primary Color: <Input onChange={this.onChange} /> </Col> <Col xs={24}> <Button type="primary" onClick={this.updateVars}> Update Vars </Button> </Col> </Row> ); } } export default ColorInput;

Github: https://github.com/mzohaibqc/antd-theme-generator

Example Code: https://github.com/mzohaibqc/antd-theme-generator/tree/master/examples/customize-cra

Live Demo: https://mzohaibqc.github.io/antd-theme-generator/

Don’t forget to clap here and like on Github if it solves your problem.