Next Js with react-xarrows gives error "ReferenceError: Element is not defined"

Viewed 1069

I am trying to build an app where I want to display arrows connecting between components. A great project I found was react-xarrows, however when I am trying to use it in my code, I see an error:

ReferenceError: Element is not defined.

enter image description here

Following is my tsconfig.js

{
  "compilerOptions": {
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "target": "es5"
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}
1 Answers

The error is most likely occurring because react-xarrows uses the DOM API which is not available on the server during server-side rendering.

To solve that, you could dynamically import react-xarrows with ssr: false to only load it on the client-side.

// Component where 'react-xarrows' is used

import dynamic from 'next/dynamic';

const Xarrow = dynamic(() => import('react-xarrows'), {
    ssr: false
});
Related