Add dark mode to your react+redux-toolkit+tailwindcss project like a pro ๐Ÿ’ช.

Add dark mode to your react+redux-toolkit+tailwindcss project like a pro ๐Ÿ’ช.

ยท

2 min read

Hi there, in this article I am going to help you add a dark Mode theme to your project (react+redux-toolkit+tailwindcss) in a matter of seconds.

So first of all you have to create a slice called "UISLICE "

import { createSlice } from "@reduxjs/toolkit";

const initialState = {

  isDarkMode:
    localStorage.getItem("isDarkMode") != undefined
      ? JSON.parse(localStorage.getItem("isDarkMode"))
      : false,//light mode is the default
};

export const uiSlice = createSlice({
  name: "ui",
  initialState,
  reducers: {


    toggleMode: (state) => {
      state.isDarkMode = !state.isDarkMode;
      localStorage.setItem("isDarkMode", state.isDarkMode);
    },
  },
});


export const { toggleMode } = uiSlice.actions;

export default uiSlice.reducer;

then add this slice to your store config

import { configureStore } from "@reduxjs/toolkit";


import { uiSlice } from "./slices/uislice";

export const store = configureStore({
  reducer: {
    ui: uiSlice.reducer,
  },

});

After this step now you create the DarkModeToggler component

import React, { useEffect } from "react";

import { Icon } from "@iconify/react";

//redux
import { useSelector, useDispatch } from "react-redux";

//Actions
import { toggleMode } from "../store/slices/uislice";

const DarkModeToggler = () => {
  const isDarkMode = useSelector((content) => content.ui.isDarkMode);
  const dispatch = useDispatch();

  const toggleModeHandler = () => {
    dispatch(toggleMode());
  };

  return (
    <div>
      <Icon
        onClick={toggleModeHandler}
        icon={isDarkMode ? "circum:dark" : "iconamoon:mode-light"}
        className="text-3xl cursor-pointer dark:text-white"
      />
    </div>
  );
};

export default DarkModeToggler;

I used @Iconfiy for adding icons you can use whatever icon package you are working with

Now in your App.jsx or the container component add this line (Don't forget to import useSelector )

 const isDarkMode = useSelector((content) => content.ui.isDarkMode);

and add this className

className={`${isDarkMode ? "dark" : ""}`}

Then you add the darkModeToggler wherever you want in your app for example in app.jsx

The final step is if you want the dark mode style to apply to a jsx element all you have to do is add this line in CSS

 dark:bg-red-100

you change "bg-red-100" by whatever tailwindcss className you want

Now you have to add this class to the components you want to change their style in dark mode

Now finally you have implemented dark mode successfully in your app ๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰

ย