0

I have 2 repos, one that houses all my components that gets packaged and uploaded to a private feed, and one that consumes them. Both repos use React and TS with the repo that consumes the package also running Next.js

I built a charting component using Plottable.js and D3 in the components repo.

Upon installing the latest version of my package onto my main repo, I'm getting build errors that say,

ReferenceError: window is not defined
    at Object.StiW (...\source\repos\njs-app\.next\serverless\pages\post.js:47656:19)
    at __webpack_require__ (...\source\repos\njs-app\.next\serverless\pages\post.js:23:31)

Going to the first line that it mentions:

var nativeArray = window.Array;

The call to the function that renders the graph and my only call to window within the function that generates the graph

export const ChartComponent = ({data, currentValue}: PlotProps) => {
    const makeBasicChart = () => {
        ...
        ...
        ...
        if (typeof window !== "undefined") {
            window.addEventListener("resize", () => plots.redraw());
        }
    }

    React.useEffect(() => {
        makeBasicChart();
    });

    return (
        <ChartContainer id="Chart"/>
    );
}

I'm receiving these errors without even including the component on a page.

I'm compiling my components repo with the TS compiler tsc and haven't had any issues until I included the charting component.

What do I need to do to resolve this issue?

Damian Jacobs
  • 488
  • 6
  • 21

3 Answers3

2

The best solution for this is to make dynamic loading.

This way your component won't even be rendered on the server-side at all.

For example:

import dynamic from 'next/dynamic';
const OrganizationChart = dynamic(() => import('@dabeng/react-orgchart'), { ssr: false });
Jc John
  • 1,799
  • 2
  • 34
  • 69
  • When trying this I am getting another error saying that "OrganizationChart" is not a function. Any idea on that? @JcJohn - any help is appreciated – mrk Dec 16 '22 at 20:07
0

Check if window is defined before you call it

Next.js renders server side so this means that there's no window object. You should wrap any code that uses window in this check

if (typeof window !== "undefined") {
  // code that uses window
}

Window will also exists any time a component is mounted so you can use window in actions like onClick and also the hook useEffect

Joe Lloyd
  • 19,471
  • 7
  • 53
  • 81
0

On SSR window is not available because its a browser based property, so its giving error.

You can avoid that error by doing this.

if (process.browser) {
   // Your window based work. 
}

For D3 based work you can initiate once the dom has ready. Better use useEffect

Monzoor Tamal
  • 790
  • 5
  • 15