ECharts
Responsive
Resize chart on window and container changes, with cleanup.
By EZ4Code Team
echartsresponsive
Code
<!-- Sized container drives the chart -->
<div id="chart" style="width: 100%; height: 400px;"></div>
<script>
const dom = document.getElementById('chart');
const chart = echarts.init(dom);
function resize() { chart.resize(); }
window.addEventListener('resize', resize);
chart.setOption({ /* options */ });
// Observe container size changes (e.g. sidebar collapse)
const ro = new ResizeObserver(() => chart.resize());
ro.observe(dom);
// Cleanup when removed
function destroy() {
window.removeEventListener('resize', resize);
ro.disconnect();
chart.dispose();
}
// React/Vue pattern: call destroy() on unmount
</script>Explanation
ECharts does not auto-detect container changes, so window resize must call chart.resize(). For layout-driven changes (collapsing sidebars, flex resizing), wrap the chart in a ResizeObserver that calls resize() on every observed change. Always call chart.dispose() and disconnect listeners on teardown to avoid memory leaks in SPA routes.
More ECharts Snippets
Bar Chart
Category bar chart with axis tooltip and styled bars.
Line Chart
Smooth multi-series line chart with area fill.
Pie Chart
Donut-style pie with emphasis effect and percentage labels.
Scatter Plot
Scatter plot with point size encoded by a third dimension.
Radar Chart
Radar with multiple indicators and overlaid value series.
Options & Series
Dataset-driven multi-series chart with grid and legend config.