1.0.6 • Published 4 years ago

react-use-browser-theme v1.0.6

Weekly downloads
41
License
MIT
Repository
github
Last release
4 years ago

react-use-browser-theme

React hook for retrieving the current browser theme and listening for changes.

npm npm

Description

This is a React Hook that will call a callback function provided to it every time the theme changes. The theme of the browser is returned as light or dark, light being the default if there is no explicit theme setting by the user.

Example

here

Install

yarn add react-use-browser-theme

or

npm install --save react-use-browser-theme

Usage

import React, { useState, useCallback, useLayoutEffect } from 'react'

import { useBrowserThemeChangeListener } from 'react-use-browser-theme'

const App = () => {
  const [theme, setTheme] = useState('light')

  useLayoutEffect(() => {
    if (matchMedia('(prefers-color-scheme: dark)').matches) {
      setTheme('dark')
    }
  }, [])

  const browserThemeListener = useCallback(
    (e) => setTheme(e.matches ? 'dark' : 'light'),
    []
  )

  useBrowserThemeChangeListener(browserThemeListener)

  return (
    <div
      style={{
        minHeight: '100vh',
        minWidth: '100vw',
        color: `${theme === 'dark' ? 'white' : 'black'}`,
        backgroundColor: `${theme === 'dark' ? 'black' : 'white'}`,
      }}
    >
      Current browser theme: {theme}
    </div>
  )
}

export default App

License

MIT © emzoumpo

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago