Dark Mode Switch

Dark Mode Switch

Installation

Install Dependencies

npm i clsx tailwind-merge framer-motion
npm i react-icons

Create @/utils/cn.ts file

import clsx, { ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

Dark Mode Component

"use client";
import { motion } from "framer-motion";
import { useState } from "react";
import { IoMoonOutline, IoSunnyOutline } from "react-icons/io5";

export default function DarkModeToggle() {
  // Implement your logic to set your theme. If using Next.JS, we recommend that you use the useTheme hook from 'next-themes'
  const [theme, setTheme] = useState("light");

  return (
    <button
      className={`flex h-8 w-14 items-center rounded-full ${theme === "dark" ? "bg-gray-500" : "bg-white"} shadow transition duration-300 focus:outline-none`}
      onClick={() => {
        if (theme === "dark") {
          setTheme("light");
        } else {
          setTheme("dark");
        }
      }}
    >
      <motion.div
        className="relative flex h-7 w-7 items-center justify-center rounded-full p-1 text-white"
        initial={false}
        animate={{
          x: theme === "dark" ? 26 : 1,
          backgroundColor: theme === "dark" ? "#374151" : "#FBBF24"
        }}
        transition={{
          type: "spring",
          stiffness: 400,
          damping: 30
        }}
      >
        {theme === "dark" ? <IoMoonOutline size={18} /> : <IoSunnyOutline size={20} />}
      </motion.div>
    </button>
  );
}