Can't get React charts running on Next.js
I am on the latest Next.js version and I can't seem to get React charts working.
Here's my package.json file for versions:
{ "name": "next13-demo", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "@types/node": "18.11.9", "@types/react": "18.0.25", "@types/react-dom": "18.0.8", "eslint": "8.27.0", "eslint-config-next": "^13.0.3", "next": "^13.0.3", "react": "^18.2.0", "react-dom": "^18.2.0", "typescript": "4.8.4" }, "devDependencies": { "autoprefixer": "^10.4.13", "postcss": "^8.4.19", "tailwindcss": "^3.2.4" } }
The file where I am trying to display the charts: `import React from 'react' import dynamic from 'next/dynamic';
const Chart = dynamic(() => import("react-charts").then((mod) => mod.Chart), { ssr: false, }); const AxisOptions = dynamic(() => import("react-charts").then((mod) => mod.AxisOptions), { ssr: false, }); type MyDatum = { date: Date, stars: number }
export default function MyChart() { const data = [ { label: 'React Charts', data: [ { date: new Date(), stars: 23467238, }, ], }, ]
const primaryAxis = React.useMemo( (): AxisOptions<MyDatum> => ({ getValue: datum => datum.date, }), [] )
const secondaryAxes = React.useMemo( (): AxisOptions<MyDatum>[] => [ { getValue: datum => datum.stars, }, ], [] )
return ( <Chart options={{ data, primaryAxis, secondaryAxes, }} /> ) }`
The error I am getting: ` error - ./node_modules/react-charts/lib/utils/buildAxis.linear.js:18:20 Module not found: ESM packages (d3-time-format) need to be imported. Use 'import' to reference the package instead. https://nextjs.org/docs/messages/import-esm-externals
Import trace for requested module: ./node_modules/react-charts/lib/components/Chart.js ./node_modules/react-charts/lib/index.js ./app/dashboard/charts.tsx ./app/page.tsx ./node_modules/next/dist/build/webpack/loaders/next-app-loader.js?name=app%2Fpage&appPaths=%2Fpage&pagePath=private-next-app-dir%2Fpage.tsx&appDir=%2FUsers%2Fanuragkanoria%2FDocuments%2Fwebprojects%2Fnext13-demo%2Fapp&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js&rootDir=%2FUsers%2Fanuragkanoria%2FDocuments%2Fwebprojects%2Fnext13-demo&isDev=true&tsconfigPath=tsconfig.json!
https://nextjs.org/docs/messages/module-not-found `
If I add esmExternals: 'loose' in next.config.js I get this error:
Error: React.createContext is not a function
I also ran into this, you can work around it by using next/dynamic and disabling SSR. Not the cleanest but works. IIRC this is a problem of an upstream dependency no longer shipping CJS
import type { Chart as ChartType } from 'react-charts'
const Chart = dynamic(() => import('react-charts').then((mod) => mod.Chart), {
ssr: false,
}) as typeof ChartType
This fixed my issue const Chart = dynamic(() => import("react-charts").then((mod) => mod.Chart), { ssr: false });