Skip to main content
Version: Next

ThemeToggler Component

The ThemeToggler component provides a user-friendly interface for switching between light, dark, and system color themes in a Next.js application. It leverages the next-themes library for theme management and custom UI components for the dropdown menu.


Installation

Ensure you have the necessary dependencies installed:

npm install next-themes lucide-react

Usage

  1. Import the ThemeToggler component:
import { ThemeToggler } from '@/components/ThemeToggler';
  1. Use the component in your layout or navigation:
<nav>
{/* Other navigation items */}
<ThemeToggler />
</nav>

Key Features

  1. Theme Toggle Button: Displays sun and moon icons that visually represent the current theme.
  2. Dropdown Menu: Opens when clicked, allowing theme selection.
  3. Theme Options: Allows users to choose between Light, Dark, and System themes.
  4. Automatic Theme Update: Changes the application's theme when a selection is made.

Styling

The component uses Tailwind CSS for styling:

  • Icons are sized using h-5 w-5 classes.
  • Transitions are applied with transition-transform for smooth animations.
  • The dark: prefix applies styles specifically in dark mode.

Accessibility

The ThemeToggler component includes several accessibility features:

  • The main button has an aria-label describing its function.
  • A visually hidden <span> with "Toggle theme" text is included for screen readers.
  • The dropdown menu inherits accessibility features from the DropdownMenu component.

Best Practices

  1. Ensure the next-themes provider is properly set up in your application.
  2. Place the ThemeToggler in a consistent location, typically in the header or navigation bar.
  3. Consider adding keyboard shortcuts for quick theme switching.

Customization

To customize the ThemeToggler component:

  1. Modify the icons or add additional theme options if needed.
  2. Adjust the Tailwind classes to match your design system.
  3. Extend the component to include additional functionality, such as theme previews.

Troubleshooting

  • Theme Not Changing: Ensure the next-themes provider is wrapping your application.
  • Icons Not Visible: Check that the Lucide React icons are properly imported and the classes are correct.
  • Dropdown Not Working: Verify that all the necessary dropdown components are imported and used correctly.

Your ThemeToggler component is now ready to use! 🎉Next steps: Integrate the ThemeToggler into your layout and test across different pages.