Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js: How to dynamically import external client-side only React components into Server-Side-Rendering apps developed?

I know this question has been asked multiple times before but none of the solution seems to work.

I'm trying to use the library 'react-chat-popup' which only renders on client side in a SSR app.(built using next.js framework) The normal way to use this library is to call import {Chat} from 'react-chat-popup' and then render it directly as <Chat/>.

The solution I have found for SSR apps is to check if typedef of window !=== 'undefined' in the componentDidMount method before dynamically importing the library as importing the library normally alone would already cause the window is not defined error. So I found the link https://github.com/zeit/next.js/issues/2940 which suggested the following:

Chat = dynamic(import('react-chat-popup').then(m => {
  const {Foo} = m;
  Foo.__webpackChunkName = m.__webpackChunkName;
  return Foo;
}));

However, my foo object becomes null when I do this. When I print out the m object in the callback, i get {"__webpackChunkName":"react_chat_popup_6445a148970fe64a2d707d15c41abb03"} How do I properly import the library and start using the <Chat/> element in this case?

like image 948
Lew Wei Hao Avatar asked Aug 09 '18 08:08

Lew Wei Hao


People also ask

How do I import component dynamically into React?

In React, dynamically importing a component is easy—you invoke React. lazy with the standard dynamic import syntax and specify a fallback UI. When the component renders for the first time, React will load that module and swap it in.

Can Next.js do client-side rendering?

Next. JS generally frowns on Client-Side Rendering, but that doesn't mean you can't fetch data from the Client at run time.

Is Next.js server-side or client-side?

Next. js is used for server side rendering of react application . React along with other framework like angular and vue. js are traditional client side framework ,they run in browser but there are technology to run this framework on server side, and next.

Can we use getServerSideProps in a component?

getServerSideProps can only be exported from a page. You can't export it from non-page files. Note that you must export getServerSideProps as a standalone function — it will not work if you add getServerSideProps as a property of the page component.


1 Answers

Next js now has its own way of doing dynamic imports with no SSR.

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(
  () => import('../components/hello3'),
  { ssr: false }
)

Here is the link of their docs: next js

like image 143
Adrian Gonzalez Avatar answered Oct 04 '22 18:10

Adrian Gonzalez