DoneDeal0
DoneDeal0

Reputation: 6257

How to use a client-side component in NextJS?

I would like to use a D3 based React Component called react-wordcloud. It works great in React, but makes Nextjs crash with the following error:

Server Error Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Based on several articles, I've tried wrote the following workarounds:

// WORKAROUND 1
{typeof window === "undefined" ? 
     <div>loading...</div>) :  
     <WordCloud words={words} />
 }
 
 // WORKAROUND 2
{process.browser && <WordCloud words={words} />}

 // WORKAROUND 3
{process.browser && 
  <div suppressHydrationWarning>
  <WordCloud words={words} />
  </div>
}

 // WORKAROUND 4
<div suppressHydrationWarning>
<WordCloud words={words} />
</div>

None of them work. The build keeps crashing. Is there any solution to force NextJS to display a client-side component?

Upvotes: 4

Views: 18956

Answers (1)

LongLegJim
LongLegJim

Reputation: 305

In Next to render a component on the client-side only, you'll need to use next/dynamic. This will prevent the rendering of a component on the server, even if the page rendering the component is using SSR or SSG.

In the WordCloud component dynamic can be used like this:

import dynamic from 'next/dynamic'

const ReactWordCloud = dynamic(() => import('react-wordcloud'), {
  ssr: false,
})

export default function WordCloud({words}){
  return (
    <ReactWordCloud words={words}/>
  )
}

https://nextjs.org/docs/advanced-features/dynamic-import

Upvotes: 11

Related Questions