1

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();
  }
m4tt
  • 825
  • 1
  • 11
  • 28
  • Does this help answer your question: [Why am I getting ReferenceError: self is not defined in Next.js when I try to import a client-side library?](https://stackoverflow.com/a/66100185/1870780)? – juliomalves Mar 03 '21 at 15:10
  • @juliomalves almost, I also thought of the component trick the problem is what i'm importing isn't a component rather a function, exported from that module .js file – m4tt Mar 03 '21 at 15:36
  • That's also the case in the question I linked. – juliomalves Mar 03 '21 at 18:18

1 Answers1

1

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();
}
juliomalves
  • 42,130
  • 20
  • 150
  • 146