reactjstypescriptchart.jsreact-chartjs-2remix.run

Can't get Remix.run and Chart.js to work together, what am I doing wrong?


I'm facing a problem with Remix.run and chart.js (react-chartjs-2) where I try and get the chart to show.

I installed the required dependencies according to the docs: react-chartjs-2 and chart.js.

Extract from package.json:

"chart.js": "^4.0.0",
"react-chartjs-2": "^5.0.0",

I decided to get the example from docs:

import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js/auto';
import { Line } from 'react-chartjs-2';
import faker from 'faker';

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
);

export const options = {
  responsive: true,
  plugins: {
    legend: {
      position: 'top' as const,
    },
    title: {
      display: true,
      text: 'Chart.js Line Chart',
    },
  },
};

const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];

export const data = {
  labels,
  datasets: [
    {
      label: 'Dataset 1',
      data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })),
      borderColor: 'rgb(255, 99, 132)',
      backgroundColor: 'rgba(255, 99, 132, 0.5)',
    },
    {
      label: 'Dataset 2',
      data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })),
      borderColor: 'rgb(53, 162, 235)',
      backgroundColor: 'rgba(53, 162, 235, 0.5)',
    },
  ],
};

export default function App() {
  return <Line options={options} data={data} />;
}

The code simply doesn't seem to be doing anything, however I could spot a little canvas element when I inspected the element.

I then took the same as above, created a new react app with create-react-app and it worked. So my assumption is that Remix is the issue here. What causes this problem?


Solution

  • Here's a sample using Chart.js with Remix.

    https://stackblitz.com/edit/remix-run-remix-dbe16z?file=README.md

    Since Remix renders your components on the server as well as the client, some React components are not SSR-friendly. They may try to access the window object, for example.

    We wrap the chart components inside the <ClientOnly> component from remix-utils.

    enter image description here