Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-css-theme-switcher

Package Overview
Dependencies
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-css-theme-switcher

Switch between CSS themes using React

  • 0.3.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
6.1K
decreased by-13.34%
Maintainers
1
Weekly downloads
 
Created
Source

React CSS Theme Switcher

Version License: MIT codecov PRs Welcome Bundle size

💫 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):


Jose Felix

💻 📖 ⚠️

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

Show your support

Give a ⭐️ if this project helped you!

Keywords

FAQs

Package last updated on 22 May 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc