A simple context provider for dark mode. It can be used in combination with Tailwind CSS to apply dark mode class with support for respecting the user's system preferences.
It also includes a few components that Utilise Headless UI to make a accesable menu to control the dark mode. Note: this not tested yet.
A Demo can be found here, and the source code can be found here.
npm install --save dark-mode-context
yarn add dark-mode-context
import React, { Component } from 'react'
import { DarkModeProvider,DarkModeMenu } from 'dark-mode-context'
const App = () => (
<DarkModeProvider injectDarkClass>
<div>
<h1>Hello World</h1>
<DarkModeMenu />
</div>
</DarkModeProvider>
)
import React, { Component } from 'react'
import { useDarkModeContext, DarkModeProvider } from 'dark-mode-context'
const MyButton = () => {
const {isDark, toggleDarkMode} = useDarkModeContext()
return (
<button onClick={toggleDarkMode}>
{isDark ? 'Dark Mode' : 'Light Mode'}
</button>
)
}
const App = () => (
<DarkModeProvider injectDarkClass>
<div>
<h1>Hello World</h1>
<MyButton />
</div>
</DarkModeProvider>
)
injectDarkClass
:boolean
- Whether the DarkModeProvider should start in dark mode or not. Defaults tofalse
wrapAs
:React.ElementType | undefined
- The element to wrap the children in. Defaults toundefined
darkClassName
:string
- The class name to be used for dark mode. Defaults todark
lightClassName
:string
- The class name to be used for light mode. Defaults to''
children
:React.ReactNode
- The children of the DarkModeProvider
Note: when
wrapAs
is not set, andinjectDarkClass
is set totrue
, the dark class will be added to the root element<html>
.
as
: React.ElementType - The element to be used for the menu. Defaults toReact.Fragment
className
:string | undefined
- The class name to be used for the menu. Defaults toundefined
darkBtn
:React.ReactNode
- The button to be used for dark mode. Defaults toDarkBtn
lightBtn
:React.ReactNode
- The button to be used for light mode. Defaults toLightBtn
systemBtn
:React.ReactNode
- The button to be used for system mode. Defaults toSystemBtn
menuToggleBtn
:React.ReactNode
- The button to be used for toggling the menu. Defaults toMenuToggleBtn
Note: This component requires HeadlessUI to be installed, which can be done by running
npm install --save headlessui
.
onClick
:() => void
- The function to be called when the button is clicked. Defaults toundefined
className
:string | undefined
- The class name to be used for the button. Defaults toundefined
Note: These components uses Tailwind CSS to style the button. they can be styled by passing a class name to the
className
prop.
MIT © NatoNathan