How to implement dark mode in React
Dark mode has become a popular feature in many apps and websites because of its benefits for user experience. Implementing dark mode in a project can be a useful skill to have, and using ReactJS and Chakra UI make it easy to do. In this tutorial, I will go through the steps necessary to implement dark mode in a ReactJS project with the help of Chakra UI, a library for ReactJS. By the end of this tutorial, you will have a website that can toggle between light and dark modes.
First step
In this tutorial, we will use Chakra UI library and its built-in functions to implement dark mode in ReactJS.
To get started with Chakra UI, you will need to install it in your project by running the following command in your terminal: “npm i @chakra-ui/react @emotion/react @emotion/styled framer-motion”.
For more information about Chakra UI: https://chakra-ui.com/
With Chakra UI now installed, we are ready to begin implementing dark mode.
Second step
The next step is to create a Theme.js file where we will define our theme information.
In Theme.js first import:
Next, open the index.css file. This file gets made in the React app-making process. Copy the information from this file and store it in your clipboard, you can now delete it from index.css.
Navigate back to theme.js and make a const, which will consist of two parts. The first part is config, where we will set some configurations. The second part is the information copied from the index.css file inside of “style:” and “body:”, like shown below.
The config also consists of two parts, two variables, initialColorMode, which will determine which mode is the default. Then the second variable, useSystemColorMode, should be set to true here.
To access this constant in other parts of our code we have to export it:
The extendTheme is a function from ChakraUI.
Third step
To enable dark mode add “ColorModeScript” with its shown props to the index.js file. It is necessary to have “ChakraProvider” around the Chakra element, as seen below.
Fourth step
To add a toggle switch for dark mode, locate the component where you want to place the switch and make a ‘colorMode’ constant with the ‘useColorMode’ function Chakra UI provides.
PS: Remember to import “useColorMode” from ChakraUI.
Next, create a button and add ‘toggleColorMode’ as its onClick action:
By doing this you will create a toggle button that displays “Dark” or “Light” depending on the current theme and allows users to switch between the two modes by clicking the button.
Once the toggle switch is implemented in your application, users should be able to switch between dark and light modes by clicking the button. The appearance of the website should then change accordingly.
Hope this tutorial was helpful and that you are now able to create a dynamic and user-friendly website with the ability to switch between light and dark modes. Good luck with your project and ask in the comments if something was unclear. Take care!