Import a Libary when Window is initalized
Answered
Giant panda posted this in #help-forum
Giant pandaOP
.
Answered by Eric Burel
Actually scratch that: in case of OP it was indeed next/dynamic because the issue comes from another lib
18 Replies
Im using a Libary and it needs to be initalized when page is fully loaded or window
How can i do that?
Ping me on anything new please thanks
use
https://nextjs-faq.com/browser-api-client-component#using-nextdynamic-with-ssr-false
next/dynamic to import the component with ssr disablehttps://nextjs-faq.com/browser-api-client-component#using-nextdynamic-with-ssr-false
@Giant panda
Sorry for the bit of self promotion but I've seen this issue so many time that I've crafted a paid (but not too expensive) course on the topic https://course.nextjspatterns.com/manage-client-only-code-in-next-js-with-react-browser-components
I am still waiting for a summary article to be published (this one will be free)
anyway, it kinda depends on your use case, there are different ways to handle this
here is a stack overflow where I quickly recap them
so if you need to render based on the window object:
- you can use "useEffect" and a ref to manipulate the DOM instead
- you can use a "useClient" hook, and render based on window when its true <- probably the right solution for you
- you can use "useEffect" and a ref to manipulate the DOM instead
- you can use a "useClient" hook, and render based on window when its true <- probably the right solution for you
@Ray next/dynamic is recommended only if you import a library that rely on window like leaflet or jquery, or if you are going to write such a library yourself (eg you have a big big chunk of code that will need window like everywhere all the time)
that's the bazooka, and the price is that the component will be rendered asynchronously server-side : need to load an additional JS file, wait for it etc.
and you completely lose SSR if you want to render a skeleton/loader to limit layout shift
Actually scratch that: in case of OP it was indeed next/dynamic because the issue comes from another lib
Answer
but this lib seems quite bad that's normally something you see only in non-React code eg Leaflet etc.
however the code shown by OP doesn't match the title, it's not the lib import that fail but the render here