Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically import a library with next.js [duplicate]

Is there a way to dynamically import a library into my next.js project? or have it load in after the initial page load? I'm looking to dynamically import the toastify library below as it's not really needed until someone clicks on an element on the page.

Tried the following but no luck:

import dynamic from 'next/dynamic'

const { ToastContainer, toast } = dynamic(import('react-toastify'), { ssr: false });
like image 325
StackUnderFlow Avatar asked Dec 02 '25 09:12

StackUnderFlow


1 Answers

Dynamic imports in Nextjs

import dynamic from 'next/dynamic'

const DynamicComponent = dynamic(() => import('../components/hello'))

Named imports ../components/hello.js

export function Hello() {
  return <p>Hello!</p>
}

import

import dynamic from 'next/dynamic'

const DynamicComponent = dynamic(() =>
  import('../components/hello').then((mod) => mod.Hello)
)

multiple Named imports ../components/hello.js

export function Hello() {
  return <p>Hello!</p>
}
export function By() {
  return <p>By!</p>
}

import

import dynamic from 'next/dynamic'

const {Hello,By}= dynamic(() =>
  import('../components/hello').then((mod) => mod),{ssr:false}
)
like image 53
Rahul Avatar answered Dec 04 '25 04:12

Rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!