Theme Provider
Overview
The ThemeProvider component is a crucial part of KnoxUI React that enables theming and dark mode functionality in your application. It wraps your entire app and provides theme context to all KnoxUI components.
Usage
To use ThemeProvider, wrap your application's root component with it:
import { ThemeProvider } from 'knoxui-react';
export default function App({ children }) {
return (
<ThemeProvider attribute="class" defaultTheme="light">
{children}
</ThemeProvider>
);
}
Props
- attribute (string): The attribute to apply to the html element. Default is "class".
- defaultTheme (string): The default theme to use. Can be "light" or "dark". Default is "light".
- storageKey (string): The key to use for storing the theme preference in localStorage. Default is "theme".
useTheme Hook
KnoxUI provides a useTheme hook that allows you to access and modify the current theme from any component:
import { useTheme } from 'knoxui-react';
function MyComponent() {
const { theme, setTheme } = useTheme();
return (
<button onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}>
Toggle theme
</button>
);
}
Live Example
Here's a live example of using the useTheme hook to toggle between light and dark themes:
Current theme: system
Best Practices
- Always wrap your entire application with ThemeProvider to ensure consistent theming across all components.
- Use the useTheme hook to access the current theme and theme-switching functionality in your components.
- Consider user preferences by respecting the system's color scheme or allowing users to manually select their preferred theme.
- Ensure all your custom components and styles are compatible with both light and dark themes for a seamless user experience.