Search code examples
reactjsfrontendnext.jshtml2canvas

How to use html2canvas with nextjs


I am using html2canvas in nextjs. As nextjs does server side rendering it is difficult to use html2canvas in nextjs.
I used the dynamic library provided by nextjs to import html2canvas,now I don't know how to use html2canvas function after import as written in html2canvas's documentation.

Importing html2canvas

const html2canvas = dynamic(() => import('html2canvas'),{ssr:false})

when I run below step as written in doc,the output of error says

"html2canvas is not a function"

html2canvas(document.body).then(function(canvas) {
    document.body.appendChild(canvas);
});

I want to know how can I use it.


Solution

  • Nextjs dynamic import is used on importing react components. If you want to import a node module you can use normal javascript based dynamic import like below

    import('html2canvas').then(html2canvas => {
      html2canvas.default(document.body).then(canvas => 
        document.body.appendChild(canvas)
      )
    }).catch(e => {console("load failed")})