Switching between themes in react and antd
Tushar Tambe
Application Developer @ThoughtWorksYou must have come across websites where you can switch between themes. You also want to create one in your react app with very less effort? This blog cum tutorial will solve your problem.
antd
#
Little about Antd also known as Ant Design is an open source component library for React. Antd provides very large set of ready made components with built in styling. You can explore and play with it here.
Antd also supports customizing themes using less variables. We are not going to customize any theme, instead we will be using predefined light and dark theme in antd.
#
Creating new react appCreate new react boilerplate app with help of create-react-app
Start the app
#
Add antdNow lets add antd as dependency in out react project.
#
Importing antd theme stylesWe need to create less stylesheets and import antd styles in it.
So lets create our two .less
files under src/themes/
directory.
dark-theme.js
light-theme.js
We will use antd defined theme colors, for that import antd theme color variables in our file.
light-theme.less
dark-theme.less
you can change default antd colors by overriding there variables in our theme files. Check antd color variables:
#
Compiling our theme filesNow we have to compile less variables to css and add them to public folder so that can be injected in client.
To compile less files into css we will use gulp task runner lets add gulp and other necessary dependencies.
now create gulpfile.js
at root level of project.
to compile less to css, lets run following command
now all less files are compiled to css and you can see it under public/
directory.
#
Switching themesNow we have done all this work of loading antd themes and compiling them to css but how to use it?
To swap between pre-fetched css styling we will use React CSS Theme Switcher
Add React CSS Theme Switcher
as dependency
now wrap our App
component with ThemeSwitcherProvider
in index.js
as following with defined themes.
index.js
Now switch between themes using useThemeSwitcher
of react-css-theme-switcher
and you're done. Now you can switch between themes🎉.
tip
Code is available on github.