ECharts with React.js on Next.js Setup with Working Code Example

tanut aran
2 min readJul 7, 2024

--

Installation

You need both echarts and React’s binding echarts-for-react

yarn add echarts-for-react echarts

Problem 1 : Import echarts

The echarts import must be

// CORRECT
import * as echarts from 'echarts';

// CORRECT
const echarts = require('echarts');

// WRONG
import echarts from 'echarts';

Problem 2 : Server Side Rendering

… React Class Component being rendered in a Server Component, React Class Components only works in Client Components.

This will solve with 'use client'

Working Code Example

Create Next.js app and replace the following in the page.tsx

We try to plot the simple line chart from the official site https://echarts.apache.org/examples/en/editor.html?c=line-simple

'use client'
import React from 'react';
import ReactECharts from 'echarts-for-react';

export default function Home() {
const option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line'
}
]
};

return <ReactECharts option={option} style={{height: '500px'}}/>;
}

Hope this help !

--

--