bootstrap-switch-button-react
bootstrap-switch-button-react copied to clipboard
SSR client side error "window is not defined"
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
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
}
)
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.