@a1knla/react-dark-mode
TypeScript icon, indicating that this package has built-in type declarations

1.0.4 • Public • Published

React Dark Mode

Typescript Typescript

Wraps system dark mode in a React hook. Make dark mode integration as simple as it should be!

Hook

useDarkMode is the only exported function of this package and this is how you use it:

import { useDarkMode } from "@a1knla/react-dark-mode"

export default function MyComponent() {
    const isDarkMode = useDarkMode()

    return (
        <>
            Current mode: {isDarkMode ? "dark" : "light"}. Try changing your system
            settings and this will update automatically.
        </>
    )
}

Sync MUI/JoyUI's dark mode with system

MUI and JoyUI have their own dark mode systems. Now you can sync them with the system dark mode:

import { useColorScheme } from "@mui/joy"
import { useDarkMode } from "@a1knla/react-dark-mode"

function syncMuiWithSystemDarkMode() {
    const isDarkMode = useDarkMode()
    const { setMode } = useColorScheme()

    useEffect(() => {
        setMode(isDarkMode ? "dark" : "light")
    }, [isDarkMode, setMode])
}

function App() {
    syncMuiJoyUiWithSystemDarkMode()

    // Your app code...
}

Doc

Good code documents itself:

export type DarkModeProps = {
    /**
     * Whether to detect system dark mode. Defaults to `true`.
     */
    detectSystemDarkMode?: boolean

    /**
     * Whether to automatically set dark mode according to local time. Defaults to `false`, and 18:00 - 6:00 is considered as night time.
     */
    detectTimeBasedDarkMode?: boolean

    /**
     * The interval to detect time based dark mode. Defaults to `1000`.
     */
    timeDetectionIntervalMillis?: number

    /**
     * Custom predicate to determine whether it's night time.
     */
    customNightTimePredicate?: () => boolean
}

export function useDarkMode(props?: DarkModeProps): boolean

Package Sidebar

Install

npm i @a1knla/react-dark-mode

Weekly Downloads

1

Version

1.0.4

License

MIT

Unpacked Size

5.13 kB

Total Files

5

Last publish

Collaborators

  • a1knla