Setting up useState in React
Here is my initial code for this project. In this project, I have a button here that does nothing when I click on it right now. We will make it into a button that lets us switch between dark and light modes. The first thing is to import usestate hook to track the states here. When the website loads for the first time, I want it to be in light mode by default and the user can later toggle it to dark mode. For this, I will set the initial state of the usestate hook to true.
Here is the implementation of usestate hook
Creating callback function
Inside the button, I will add an event handler , onClick and use the callback function to toggle between light and dark. Now, I will create the callback function under the usestate hook as follows. I will add ternary operator inside the button so that different text appear when the state changes.
Editing Tailwind.config.js
We now have a button that changes according to the state. Now, we will start the implementation inside tailwindcss. First, go to tailwind.config.js and enter darkMode = ‘class’. Use dark as a prefix inside the classname to enable dark mode and add dark mode as needed inside your components.
Adding ClassList to handleClick
Lastly, we will use document.body inside the handleclick function to alter the appearance to dark mode.