chartjs-plugin-zoom icon indicating copy to clipboard operation
chartjs-plugin-zoom copied to clipboard

enable to use in SSR framework like Next.js and Nuxt.js

Open jhlee910609 opened this issue 1 year ago • 7 comments

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.

jhlee910609 avatar Mar 10 '23 06:03 jhlee910609

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.

yuval-herman avatar Mar 15 '23 09:03 yuval-herman

If I recall correctly, window is required by hammer, and you can just import ng-hammer instead.

kurkle avatar May 09 '23 14:05 kurkle

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.

tgoyer avatar Jun 06 '23 20:06 tgoyer

I'm on Next 13.3 with chartjs 4.4.0, the above solution doesn't work for me.

anthonyma94 avatar Sep 11 '23 17:09 anthonyma94

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

alanrubin avatar Oct 02 '23 05:10 alanrubin

Would there be a way to change the plugin so it just works (excluding SSR) when 'use client' directive is set?

wayneschuller avatar Nov 26 '23 23:11 wayneschuller

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!

kyllerss avatar Feb 01 '24 16:02 kyllerss