Giter VIP home page Giter VIP logo

react-css-theme-switcher's Introduction

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

Name Type Default value Description
attr String data-theme Attribute name for that will be appended to the body tag. Its value will be the current theme name.
defaultTheme String Default theme to load on mount. Must be in themeMap
id String current-theme-style Id of the current selected CSS.
insertionPoint String or HTMLElement Comment 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.
themeMap Object Object with all themes available. Key is the theme name and the value is the path for the CSS file.

useThemeSwitcher

Returns

Name Type Default value Description
currentTheme String or Undefined undefined Current selected theme
themes Object themeMap keys All themes supplied in the themeMap.
switcher ({ theme }: { theme: string }) => void; Function Function to change themes.
status enum('idle', 'loading', 'loaded') idle Current 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!

react-css-theme-switcher's People

Contributors

dependabot[bot] avatar elis avatar joserfelix avatar

Stargazers

 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.