DocsDeveloper

Theme Toggle

Overview

The ThemeToggle component is a React functional component that provides a user interface element for toggling between light and dark themes in a web application. It leverages the next-themes library to manage theme switching seamlessly. This component was made to be used with the Dark Mode feature.

Demo

Click me to toggle light and dark mode!

Easy CLI Install

jrui add themeToggle

Component File

components > ThemeToggle.tsx

"use client";
import * as React from "react";
import { Moon, Sun } from "lucide-react";
import { useTheme } from "next-themes";

export default function ThemeToggle() {
  const { theme, setTheme } = useTheme();

  const toggleTheme = () => {
    setTheme(theme === "light" ? "dark" : "light");
  };

  return (
    <button onClick={toggleTheme}>
      {theme === "light" ? (
        <Sun
          className=" h-11 w-11 p-[.25rem] border-gradient card-hover"
          strokeWidth={1}
        />
      ) : (
        <Moon
          className="h-11 w-11 p-[.25rem] border-gradient card-hover"
          strokeWidth={1}
        />
      )}
      <span className="sr-only">Toggle theme</span>
    </button>
  );
}
      

Example Use Case

Example.tsx

import React from "react";
import ThemeToggle from "./ThemeToggle"; // Adjust the import path based on your project structure

const Example: React.FC = () => {
  return (
    <Reveal className="container relative p-5 flex gap-4 flex-col center no-scroll">
        <h2>Click me to toggle light and dark mode!</h2>
        <ThemeToggle />
    </Reveal>
  );
};

export default Example;