use-color-scheme

React Hook to get users prefered color scheme

Usage no npm install needed!

<script type="module">
  import useColorScheme from 'https://cdn.skypack.dev/use-color-scheme';
</script>

README

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/use-color-scheme@1.1.1"></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