How To Use ApexCharts in a Next.js Project
Next.js is undoubtedly one of the leading meta-frameworks in the front-end landscape. But, it seems that there’s a particular problem in using Next.js with a popular charting library — ApexCharts. In this article, we will discuss what that problem is and a way to solve it.
Let’s start by initializing a new project
Here’re the command prompt to initialize a new Next.js project (I’m pretty sure you already knew how to initialize it, but just to make it easier for you so you don’t have to open up the documentation)
#npm
npx create-next-app@latest
#pnpm
pnpm create next-app
Don’t forget to install all the necessary dependencies for the ApexCharts, including its react wrapper
#npm
npm i react-apexcharts apexcharts
#pnpm
pnpm i react-apexcharts apexcharts
We’ll be using both the old trusty pages
and the new shiny app
directory. The implementation differences on both of them is not that big, so let’s get started.
In both directory types, I personally prefer the folder structure to be like this (especially the components
folder placement). You may fit in your own structure preferences
nextjs_project
├── node_modules
├── public
└── src
├── components
└── pages/app
Create the graph component
inside the components
folder, let’s create a charts.tsx/jsx
file
// charts.tsx/jsx
'use client' // if you use app dir, don't forget this line
import dynamic from "next/dynamic";
const ApexChart = dynamic(() => import("react-apexcharts"), { ssr: false });
export function ExampleChart(){
const option = {
chart: {
id: 'apexchart-example'
},
xaxis: {
categories: [1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999]
}
}
const series = [{
name: 'series-1',
data: [30, 40, 35, 50, 49, 60, 70, 91, 125]
}]
return(
<>
<ApexChart type="line" options={option} series={series} height={200} width={500} />
</>
)
}
If you try to import it as instructed in react-apexcharts — npm (npmjs.com) like this
import Chart from 'react-apexcharts'
You will likely encounter this error
or maybe it kinda looks like this in your terminal
This error is likely caused by Next.js’s auto pre-rendering (Rendering: Automatic Static Optimization | Next.js (nextjs.org)). It seems that ApexChart’s library depends on the window
interface that reside on the client side of things, so it can’t be pre-rendered on the server as of the wiriting of this article.
And so, the solution that Next.js provided us with to tackle this case is to use the built-in next/dynamic
to do dynamic import and to explicitly configure to turn off server-side pre-rendering.
'use client' // don't forget this part if you use app dir to mark the whole
// file as client-side components
import dynamic from "next/dynamic";
const Chart = dynamic(() => import("react-apexcharts"), { ssr: false });
Try it for yourself!
This one is for the pages
directory
And this one is for the app
directory
That’s all from me for now. Thanks for reading!