donavon / use-dark-mode

A custom React Hook to help you implement a "dark mode" component.
MIT License
1.28k stars 100 forks source link

`global` variable in browser context is always undefined. I think you meant `globalThis` #91

Open cpakken opened 2 years ago

cpakken commented 2 years ago

https://github.com/donavon/use-dark-mode/blob/29590271bb3a74f08975181c5ed68bd5a210ef83/src/initialize.js#L15

The global variable will only exist in node during ssr. globalThis === window in browsers and globalThis === global in node

haseeb5i commented 2 years ago

yes, i am facing the same issue. As soon i use the hook, my app crashes with an error use-dark-mode.m.js:1 Uncaught ReferenceError: global is not defined. I am using vite with react 17

The error goes away if i put var global = globalThis; in my index.html file

akshayjai1 commented 1 year ago

facing same problem

now created custom solution using https://www.thisdot.co/blog/how-to-implement-a-dark-to-light-mode-feature-in-your-react-sass-project and https://www.geeksforgeeks.org/how-to-create-dark-mode-using-prefer-color-scheme-media-query/

probablyraging commented 1 year ago

I solved this by adding window.global = globalThis in the file where I create the entry point to the DOM

Example:

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';

window.global = globalThis;

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
ttebify commented 3 months ago

This will also work:

import useDarkMode from "use-dark-mode";
import { Switch } from "@nextui-org/react";
import { SVGProps } from "react";

export const ThemeSwitcher = () => {
    const darkMode = useDarkMode(false, {
        classNameDark: "dark",
        classNameLight: "light",
        global: window, // Just pass this as a config option
    });

    return (
        <Switch
            defaultSelected={darkMode.value}
            onValueChange={darkMode.toggle}
            size="lg"
            color="warning"
            startContent={<MoonIcon />}
            endContent={<SunIcon />}
        />
    );
};