chartjs-plugin-zoom
chartjs-plugin-zoom copied to clipboard
enable to use in SSR framework like Next.js and Nuxt.js
When I use this plugin on Next.js, I cannot use this because of Error:window is not undefined
.
I guess it miss the case that use on SSR framework.
Check out #738. In essence if you want to use this with next js and ssr the zoom has no added value, you need to declare this component to be rendered on the client.
If I recall correctly, window is required by hammer
, and you can just import ng-hammer
instead.
If you need to use this in NextJS, you can use a dynamic import. Put your chart, configuration and plugins into a child component:
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend } from 'chart.js';
import { Bar } from 'react-chartjs-2';
import Zoom from 'chartjs-plugin-zoom';
ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend, Zoom);
interface Props {
labels: (string | null)[];
datasets: any[];
}
const MyChart = ({ labels, datasets }: Props) => {
return (
<Bar
options={{
plugins: {
zoom: {
zoom: {
wheel: {
enabled: true,
},
pinch: {
enabled: true,
},
mode: 'xy',
},
},
}
}}
data={{
labels: labels,
datasets: datasets,
}}
/>
);
};
export default MyChart;
Then import it in your view like:
import dynamic from 'next/dynamic';
const MyChart = dynamic(() => import('@/components/MyChart'), { ssr: false });
Then just use it in your view like normal.
<div>
<MyChart />
</div>
This will get around the window is not defined
error.
I'm on Next 13.3 with chartjs 4.4.0, the above solution doesn't work for me.
The above solution worked for me perfectly in Next 13.4 and chartjs 4.2.0 - the problem using dynamic import was that my components didn't have the default export - so I had to use the following syntax https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#with-named-exports
Would there be a way to change the plugin so it just works (excluding SSR) when 'use client' directive is set?
I'm also running into this issue. In my case, I'm using SvelteKit. I'll work around the issue, but it would be great for other first-timers to this plugin to have this be a little more forgiving in a SSR context. I can only assume the use of SSR frameworks are going to become more predominant as time progresses. Keep up the great work!