Switch between dark and light mode in your React application with ease.
npm install react-hook-themeSwitch between dark and light mode in your React application with ease.
- Provides the theme context to components
- Hook to retrieve and change the current theme
- Optional toggle to switch between dark and light mode
- Automatic detection of users' browser settings
- Optionally persists the selected theme to local storage
- Ready for Next.js
Check out the CodeSandbox for a working example.
Another example is also included in the example folder of the repository.
``bash
yarn add react-hook-theme
npm install react-hook-theme
`
Wrap the application in the ThemeProvider. Optionally provide settings via the options prop.
`typescript
/*
* index.tsx
*/
import { ThemeProvider } from 'react-hook-theme';
// ...
theme: 'dark',
save: true,
}}
>
;
// ...
`
#### Options Prop
| Name | Type | Required | Description | Default |
| ----- | ------- | -------- | ---------------------------------------- | ------- |
| theme | Theme | | The default theme as a fallback | dark |
| save | boolean | | Save theme to local storage when changed | false |
Adjust the styling of your app by utilizing css variables:
`css
/*
* style.css
*/
:root {
--background: #fff;
--primary: #000;
}
[data-theme='light'] {
--background: #fff;
--primary: #000;
}
[data-theme='dark'] {
--background: #282c34;
--primary: #fff;
}
// ...
body {
background-color: var(--background);
color: var(--primary);
}
`
Optionally use the toggle component to render a switch to change between dark and light mode.
`typescript
/*
* App.tsx
*/
import { Toggle } from 'react-hook-theme';
// styling
import 'react-hook-theme/dist/styles/style.css';
// ...
`
#### Props
| Name | Type | Required | Description | Default |
| ---- | ------ | -------- | ------------------------------------- | ---------- |
| id | string | | Sets the html id of the input element | rht-toggle |
Use the provided useTheme hook to access or update the current theme
`typescript
/*
* App.tsx
*/
import { useTheme } from 'react-hook-theme';
// ...
const { theme, setTheme } = useTheme();
``
#### Return
| Object Name | Type | Description |
| ----------- | ---------------------- | ------------------------ |
| theme | Theme | The current theme |
| setTheme | (theme: Theme) => void | Update the current theme |
| options | ThemeOptions | Configuration of hook |