react-apexcharts
react-apexcharts copied to clipboard
Support Nextjs@13 / React server components (window is not defined)
Apex Charts tries to access the window
object without checking it is available first, so it does not work in server contexts.
The workaround is to ensure the library is only used in a browser context
In NextJS, the usual method of ensuring a module only renders on the client is to use next/dyanamic
with SSR disabled, but this approach doesn't work in NextJS 13:
// nextjs13 - doesn't work - gives "window is not defined"
"use client";
import dynamic from "next/dynamic";
const Chart = dynamic(() => import("react-apexcharts"), { ssr: false });
export default function ApexChart(props: any) {
return <Chart {...props} />;
}
My current workaround is to import "react-apexcharts"
inside a useEffect to force NextJS to only import on the client side:
// nextjs13 - works
"use client";
import { useEffect, useState } from "react";
export default function ApexChart(props: any) {
const [Chart, setChart] = useState<any>();
const hasType = typeof props?.type !== "undefined";
useEffect(() => {
import("react-apexcharts").then((mod) => {
setChart(() => mod.default);
});
}, []);
return hasType && Chart && <Chart {...props} />;
}
But IMO I feel this is unnecessary if the Apex Charts library would just check that the window object is available first before trying to access it
Related issues:
- https://github.com/apexcharts/react-apexcharts/issues/425
- https://github.com/apexcharts/react-apexcharts/issues/358
- https://github.com/apexcharts/react-apexcharts/issues/240
Although not very elegant, it solved my problem. I think we should add an undefined check for the window in the project.
We're facing the same issue in our project, SSR is breaking duo to Apex Charts. A proper fix would be great. We used the useEffect
workaround, it works but it's nasty!
Yeah, i am facing this issue too. We need proper fix to solve this problem
Got hit with a similar issue today,
I'm also facing the issue. Thanks for the workaround, @lokimckay
thanks for your sample, and now i can get the ApexCharts, but when i use getChartByID
, can get nothing here.
and i check the apex id in chrome dev tool's elements tab, there is.
This solution does work for me (NextJs 14.1 app router) for Timeline charts, but unfortunately not for Scatter plots. They do not render at all.