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
- Import the ThemeToggler component:
import { ThemeToggler } from '@/components/ThemeToggler';
- Use the component in your layout or navigation:
<nav>
{/* Other navigation items */}
<ThemeToggler />
</nav>
Key Features
- Theme Toggle Button: Displays sun and moon icons that visually represent the current theme.
- Dropdown Menu: Opens when clicked, allowing theme selection.
- Theme Options: Allows users to choose between Light, Dark, and System themes.
- 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
- Ensure the
next-themes
provider is properly set up in your application. - Place the ThemeToggler in a consistent location, typically in the header or navigation bar.
- Consider adding keyboard shortcuts for quick theme switching.
Customization
To customize the ThemeToggler component:
- Modify the icons or add additional theme options if needed.
- Adjust the Tailwind classes to match your design system.
- 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.