0.3.0 • Published 3 years ago

react-css-theme-switcher v0.3.0

Weekly downloads
1,838
License
MIT
Repository
github
Last release
3 years ago

💫 Switch between CSS themes using React

Prerequisites

  • node >=10

Installation

npm i react-css-theme-switcher

or with Yarn:

yarn add react-css-theme-switcher

Usage

Import ThemeSwitcherProvider and pass a theme object with the names of the themes and their respective paths to the CSS stylesheet (normally, public folder).

import React from 'react';
import ReactDOM from 'react-dom';

import { ThemeSwitcherProvider } from 'react-css-theme-switcher';

const themes = {
  light: 'public/light.css',
  dark: 'public/dark.css',
};

const App = () => {
  return (
    <ThemeSwitcherProvider defaultTheme="light" themeMap={themes}>
      <Component />
    </ThemeSwitcherProvider>
  );
};

Use useThemeSwitcher Hook:

import { useThemeSwitcher } from 'react-css-theme-switcher';

const Component = () => {
  const { switcher, themes, currentTheme, status } = useThemeSwitcher();
  const [isDarkMode, setIsDarkMode] = React.useState(false);

  if (status === 'loading') {
    return <div>Loading styles...</div>;
  }

  const toggleDarkMode = () => {
    setIsDarkMode(previous => {
      switcher({ theme: previous ? themes.light : themes.dark });
      return !previous;
    });
  };

  return (
    <div>
      <h2>Current theme: {currentTheme}</h2>
      <button onClick={toggleDarkMode} />
    </div>
  );
};

CSS Injection Order

react-css-theme-switcher provides a way to avoid collision with other stylesheets or appended styles by providing where to inject the styles. To achieve this, add an HTML comment like <!--inject-styles-here--> somewhere on the head and then provide 'inject-styles-here' or your custom name in the insertionPoint prop in ThemeSwitcherProvider.

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      @import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');

      * {
        color: inherit;
      }

      html {
        font-family: 'Poppins', sans-serif;
      }
    </style>
    <!-- inject-styles-here -->
    <title>Playground</title>
  </head>

  <body>
    <div id="root"></div>
  </body>
</html>
const App = () => {
  return (
    <ThemeSwitcherProvider
      defaultTheme="light"
      insertionPoint="inject-styles-here"
      themeMap={themes}
    >
      <Component />
    </ThemeSwitcherProvider>
  );
};

HTML Element Insertion Point

Some libraries and frameworks make it hard to use comments in head for handling injection order. To solve this issue, you can provide a DOM element as the insertion point. Take for example a <noscript></noscript> element:

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      @import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');

      * {
        color: inherit;
      }

      html {
        font-family: 'Poppins', sans-serif;
      }
    </style>
    <noscript id="inject-styles-here"></noscript>

    <title>Playground</title>
  </head>

  <body>
    <div id="root"></div>
  </body>
</html>
const App = () => {
  return (
    <ThemeSwitcherProvider
      defaultTheme="light"
      insertionPoint={document.getElementById('inject-styles-here')}
      themeMap={themes}
    >
      <Component />
    </ThemeSwitcherProvider>
  );
};

API

ThemeSwitcherProvider

Props

NameTypeDefault valueDescription
attrStringdata-themeAttribute name for that will be appended to the body tag. Its value will be the current theme name.
defaultThemeStringDefault theme to load on mount. Must be in themeMap
idStringcurrent-theme-styleId of the current selected CSS.
insertionPointString or HTMLElementComment string or element where pre-fetch styles and current themes will be injected. The library will look for the comment string inside head element. If missing will append styles at the end of the head. This is useful for CSS override.
themeMapObjectObject with all themes available. Key is the theme name and the value is the path for the CSS file.

useThemeSwitcher

Returns

NameTypeDefault valueDescription
currentThemeString or UndefinedundefinedCurrent selected theme
themesObjectthemeMap keysAll themes supplied in the themeMap.
switcher({ theme }: { theme: string }) => void;FunctionFunction to change themes.
statusenum('idle', 'loading', 'loaded')idleCurrent load status of the selected stylesheet. Useful to prevent flicker when changing themes.

Contributors

Thanks goes to these wonderful people (emoji key):

This project follows the all-contributors specification. Contributions of any kind are welcome!

Show your support

Give a ⭐️ if this project helped you!