dark-mode-context v1.0.0-alpha.3
dark-mode-context
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.
Install
npm install --save dark-mode-context
yarn add dark-mode-contextUsage
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>
)Props
DarkModeProvider
injectDarkClass:boolean- Whether the DarkModeProvider should start in dark mode or not. Defaults tofalsewrapAs:React.ElementType | undefined- The element to wrap the children in. Defaults toundefineddarkClassName:string- The class name to be used for dark mode. Defaults todarklightClassName:string- The class name to be used for light mode. Defaults to''children:React.ReactNode- The children of the DarkModeProvider
Note: when
wrapAsis not set, andinjectDarkClassis set totrue, the dark class will be added to the root element<html>.
DarkModeMenu
as: React.ElementType - The element to be used for the menu. Defaults toReact.FragmentclassName:string | undefined- The class name to be used for the menu. Defaults toundefineddarkBtn:React.ReactNode- The button to be used for dark mode. Defaults toDarkBtnlightBtn:React.ReactNode- The button to be used for light mode. Defaults toLightBtnsystemBtn:React.ReactNode- The button to be used for system mode. Defaults toSystemBtnmenuToggleBtn: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.
DarkBtn, LightBtn, SystemBtn, MenuToggleBtn
onClick:() => void- The function to be called when the button is clicked. Defaults toundefinedclassName: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
classNameprop.
License
MIT © NatoNathan