I'm trying to use this small js library called float-sidebar.js, I've installed the module via npm, but I noticed in react it throws error "window" not defined, because "window" is used inside the code float-sidebar.min.js inside the module without checking if window loaded or ready.
Since I'm using Next.js I've tried to dynamically load the module like:
import dynamic from 'next/dynamic'
const FloatSidebar = dynamic(
() => import('float-sidebar'),
{ ssr: false }
)
doing so it doesn't throw the "window" undefined error anymore, but it says FloatSidebar
is not a function later on in my code:
const handleScroll = () => {
const sidebar = document.querySelector('.sidebar');
const relative = document.querySelector('.content');
const floatSidebar = FloatSidebar({
sidebar: sidebar,
relative: relative,
topSpacing: 40,
bottomSpacing: 40
});
floatSidebar.forceUpdate();
}
You could simply use the regular ES2020 dynamic import on float-sidebar
inside your handleScroll
callback.
const handleScroll = () => {
const sidebar = document.querySelector('.sidebar');
const relative = document.querySelector('.content');
const FloatSidebar = (await import('float-sidebar')).default;
const floatSidebar = FloatSidebar({
sidebar: sidebar,
relative: relative,
topSpacing: 40,
bottomSpacing: 40
});
floatSidebar.forceUpdate();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.