react-force-graph icon indicating copy to clipboard operation
react-force-graph copied to clipboard

"Error: Must use import to load ES Module" when importing 'react-force-graph-2d' in a NextJS project

Open TristanMinor opened this issue 3 years ago • 7 comments
trafficstars

The bug it seems like react-force-graph packages are not compatible with NextJs projects, because there is an issue with importing a d3-selection package.

To Reproduce Steps to reproduce the behavior:

  1. Install the package with pnpm i react-force-graph-2d
  2. Import it with
import ForceGraph2D from 'react-force-graph-2d`
  1. get the error:

image

Additional context I also tried solving this with dynamic import:

import dynamic from "next/dynamic"
const ForceGraph2D = dynamic(() => import('react-force-graph-2d'), {
  ssr: false
})

...but that seemed to work only in the build mode. The graph did not show up in the dev mode at all.

Versions

  • Next version: v12.2.3
  • Node version: v14.17.1

TristanMinor avatar Jul 30 '22 10:07 TristanMinor

@TristanMinor this ia nextjs specific question, but it's probably happening because you have SSR rendering enabled on your app. You can use something like react-no-ssr to disable it.

vasturiano avatar Jul 30 '22 12:07 vasturiano

@vasturiano encountered the same issue, react-no-ssr didn't help.

Would you happen to have other ideas how to resolve it?

boris-lapouga avatar Aug 01 '22 21:08 boris-lapouga

@boris-lapouga the center piece of this issue is why the framework is doing a require (commonJs) of the module. If it's due to SSR (typically is), generally disabling it and switching to dynamic imports while importing this module solves the issue. But as mentioned, this is very nextjs specific so a forum dedicated to that will probably be a better medium to pose the question.

vasturiano avatar Aug 02 '22 09:08 vasturiano

This works for me.

const ForceGraph3D = dynamic(() => import('react-force-graph-3d'), {
    ssr: false,
})

chwan1 avatar Aug 11 '22 10:08 chwan1

This works for me.

const ForceGraph3D = dynamic(() => import('react-force-graph-3d'), {
    ssr: false,
})

this works partially but breaks forward refs - ref.current always returns a {retry:fn} object

TheExGenesis avatar May 09 '23 18:05 TheExGenesis

Hi, apologies for bumping the thread, but were you able to find a solution for this? I am using const ForceGraph3D = dynamic(() => import('react-force-graph-3d'), { ssr: false, })

As mentioned, however it does break forward refs - returns {retry:fn}. All I'm trying to do now is to figure out a way to access refs so that I can access the three.js scene and modify it.

anaghkanungo7 avatar Aug 30 '23 23:08 anaghkanungo7