react-apexcharts
react-apexcharts copied to clipboard
ApexChart Not working with NextJs 13 latest
Hi, Can you check why apexchart throws multiple errors with nextJs 13. Server Error ReferenceError: window is not defined This error happened while generating the page. Any console logs will be displayed in the terminal window. even after using import dynamic from 'next/dynamic'
const Chart = dynamic(() => import('react-apexcharts'), { ssr: false });
Instead of importing react-apexcharts dynamically, create a component and import react-apexcharts normally in that component then import that component dynamically into your parent component. Here's an example of how it should look like
Parent.tsx
import dynamic from "next/dynamic";
const DynamicGraph = dynamic(() => import("@/components/Child"), {
ssr: false,
});
const Parent = () => {
return <><DynamicGraph /></>
}
export default Parent;
Child.tsx
import Chart from "react-apexcharts";
const Child = () => {
return <><Chart options={options} series={series} /></>
}
export default Child;
Is there a better/nicer solution than adding another component and doing props drilling?
I'm not sure this any nicer, but it keeps things in a single component:
const [ReactApexChart, setChart] = useState(null);
useEffect(() => {
if (typeof window !== "undefined") {
setChart(() => require("react-apexcharts").default);
}
}, []);
return ReactApexChart && <ReactApexChart />;
};
Next dynamic works for me though. I'm using Next v13.2.4 and react-apexcharts v1.4.1 i'm using appDir
import dynamic from 'next/dynamic';
const Chart = dynamic(() => import('react-apexcharts'), {
ssr: false,
});
This should be a better way
Instead of importing react-apexcharts dynamically, create a component and import react-apexcharts normally in that component then import that component dynamically into your parent component. Here's an example of how it should look like
Parent.tsx
import dynamic from "next/dynamic"; const DynamicGraph = dynamic(() => import("@/components/Child"), { ssr: false, }); const Parent = () => { return <><DynamicGraph /></> } export default Parent;
Child.tsx
import Chart from "react-apexcharts"; const Child = () => { return <><Chart options={options} series={series} /></> } export default Child;
Dynamically importing the charts alone was not the solution. This was the solution, what a pain.
React.lazy works for me:
export const ApexChart = lazy(() => import('react-apexcharts'));
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.