Skip to content

@hrc/toggle-theme

Simple component for toggle between light and dark theme in your React app

Demo generated with code from Usage section

  • It saves the theme in localStorage with the key theme
  • If there is no theme in localStorage, the default is the user’s preferred theme

Installation

Terminal window
npm install @hrc/toggle-theme

Usage

  1. Import load-theme.js in your index.html:

    <script
    type="module"
    src="node_modules/@hrc/toggle-theme/dist/load-theme.js"
    ></script>
  2. Then use the component in your project:

    import { ThemeButton } from "@hrc/toggle-theme";
    import { Icon } from "@hrc/material-icons";
    const Light = () => {
    return (
    <>
    <Icon name="light_mode" size="large" color="warning" />
    <span>Light</span>
    </>
    );
    };
    const Dark = () => {
    return (
    <>
    <Icon name="dark_mode" size="large" color="info" />
    <span>Dark</span>
    </>
    );
    };
    export function PackageDemo() {
    return <ThemeButton lightElement={<Light />} darkElement={<Dark />} />;
    }
  3. Add your styles:

    :root {
    --bg-color: #fff;
    --text-color: #17181c;
    }
    [data-theme="dark"] {
    --bg-color: #17181c;
    --text-color: #fff;
    }
    body {
    background-color: var(--bg-color);
    color: var(--text-color);
    }

Demos

For examples and details on the usage of the component, see the demo page:

API

See documentation below for reference to all of the props, classes and CSS variables (custom properties) available for toggle theme component: