Skip to content

mujo-code/use-color-scheme

Repository files navigation

Use Color Scheme

This is a React hook that allows you to hook into the browsers detection of color scheme. This will help you detect dark, light or no-preference color schemes.

Why

Because the user has explicitly asked for a preference why not let them enjoy a dark version of your application. 🌚

Swap Demo

demo page => source code

Technology Used

Prefers color scheme media query is still very new and not supported on all browsers, please see link for latest support. It will be available in Chrome (stable) July 30th 2019

Install

npm install use-color-scheme --save
## or
yarn add use-color-scheme

or just include it in your browser.

<script src="https://unpkg.com/[email protected]"></script>

React > 16.8.6 is a peer dependency and will need to installed/included as well.

Usage

It is a React hook! So import the hook then place it in the render function of a component.

import React from 'react'
import { useColorScheme } from 'use-color-scheme'

const modes = {
  dark: { background: 'black', color: 'white' },
  light: { background: 'white', color: 'black' },
}

export const MyComponent = () => {
  const { scheme } = useColorScheme()
  const style = modes[scheme] || scheme.dark

  return (
    <div style={style}>
      <h1>Your preference is: {scheme}</h1>
    </div>
  )
}

Try it out in CodePen

Useful Links

Original Inspiration

About

A React hook to get the users preferred color scheme.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published