A Tailwind CSS theme switcher that toggles dark/light mode when clicking in the top-left corner of the screen. Perfect for creating a subtle, cursor-based theme switching experience in your web applications.
darkMode: 'class'
configurationnpm install tailwind-theme-cursor-switch
darkMode: 'class'
:// tailwind.config.js
module.exports = {
darkMode: 'class',
// ... rest of your config
}
// Using ES modules
import { initThemeCursorToggle } from 'tailwind-theme-cursor-switch';
// Initialize the theme switcher
initThemeCursorToggle();
Or using CommonJS:
const { initThemeCursorToggle } = require('tailwind-theme-cursor-switch');
initThemeCursorToggle();
You can use this package in React applications in two ways:
Basic Usage (Recommended)
Initialize the theme switcher in your app's entry point (e.g., main.tsx
or App.tsx
):
// src/main.tsx or src/App.tsx
import { initThemeCursorToggle } from 'tailwind-theme-cursor-switch';
import { useEffect } from 'react';
function App() {
useEffect(() => {
initThemeCursorToggle();
}, []);
return (
// Your app content
);
}
Custom Hook Usage
Create a custom hook for more control:
// src/hooks/useThemeCursor.ts
import { useEffect } from 'react';
import { initThemeCursorToggle, Theme } from 'tailwind-theme-cursor-switch';
export function useThemeCursor() {
useEffect(() => {
const cleanup = initThemeCursorToggle();
return () => {
// Cleanup event listeners if needed
cleanup?.();
};
}, []);
}
// Usage in your component:
function App() {
useThemeCursor();
return (
// Your app content
);
}
With Next.js
For Next.js applications, initialize in your _app.tsx
or layout.tsx
:
// src/app/layout.tsx (App Router)
'use client';
import { useEffect } from 'react';
import { initThemeCursorToggle } from 'tailwind-theme-cursor-switch';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
useEffect(() => {
initThemeCursorToggle();
}, []);
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
Or with Pages Router:
// src/pages/_app.tsx
import { useEffect } from 'react';
import { initThemeCursorToggle } from 'tailwind-theme-cursor-switch';
function MyApp({ Component, pageProps }) {
useEffect(() => {
initThemeCursorToggle();
}, []);
return <Component {...pageProps} />;
}
export default MyApp;
Ensure your Tailwind configuration is set up correctly:
// tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
darkMode: 'class',
content: [
'./src/**/*.{js,jsx,ts,tsx}',
],
// ... rest of your config
}
Add dark mode styles to your global CSS:
/* src/index.css or src/styles/globals.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
/* Optional: Add smooth transitions for theme changes */
* {
@apply transition-colors duration-200;
}
storage
eventdark
class on the documentElement
The package includes TypeScript definitions. The main type export is:
type Theme = 'dark' | 'light';
This package works in all modern browsers that support:
MIT