Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SSR client side error "window is not defined" #35

Open
jerome-diver opened this issue Aug 27, 2020 · 2 comments
Open

SSR client side error "window is not defined" #35

jerome-diver opened this issue Aug 27, 2020 · 2 comments

Comments

@jerome-diver
Copy link

I try to use this module with SSR React + Express inside a Form with Bootstrap-react module, but it failed with ReferenceError: window is not defined from bootstrap-switch-button-react.js:1:9869

@arenddeboer
Copy link

In Next.js this can be solved with dynamic imports

import dynamic from 'next/dynamic'
const BootstrapSwitchButton = dynamic(
    () => import('bootstrap-switch-button-react'),
    {
        loading: () => <p>loading</p>,
        ssr: false // This line is important. It's what prevents server-side render
    }
)

@apokryfos
Copy link

apokryfos commented Jan 27, 2021

This issue seems to be from the "style-loader" module. Which uses window. functions without checking if the window is set. The general suggestion is to use isomorphic-style-loader. I've tried doing this but I did not manage to get the css to actually load (so was a pointless endeavour). Perhaps someone who understands webpack better than me can get this to work correctly.

The workaround for people using normal React with custom SSR is to have something like:

const BootstrapSwitchButtonClientSide = (props) => {
    const [ loadedState, setLoadedState ] = useState(<Fragment />);
    useEffect(() => {
        const BootstrapSwitchButton = require('bootstrap-switch-button-react').default;
        setLoadedState(<BootstrapSwitchButton {...props} />);
    }, []);

    return loadedState;
}

This should prevent the component from being rendered on the serverside, but will probably result in the button to be missing on initial render, so not ideal especially for people with slower machines. Fragment here is React.Fragment, I think you can just use null as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants