Dynamically import a library with next.js

Viewed 3926

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 });
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}
)
Related