Blog>
Snippets

Incorporating Chart.js for Data Visualization

Explain how to integrate Chart.js into Next.js by creating a dynamic chart component that visualizes API data.
import { useEffect, useState } from 'react';
import Chart from 'chart.js/auto';
import { Bar } from 'react-chartjs-2';

export default function DynamicChartComponent() {
    const [chartData, setChartData] = useState({ datasets: [] });

    useEffect(() => {
        async function fetchData() {
            const response = await fetch('api/data-endpoint');
            const data = await response.json();
            // Transform the data into chart.js format
            setChartData({
                labels: data.map(item => item.label),
                datasets: [{
                    label: 'Dataset 1',
                    data: data.map(item => item.value),
                    backgroundColor: 'rgba(255, 99, 132, 0.5)',
                    borderColor: 'rgb(255, 99, 132)',
                    borderWidth: 1
                }]
            });
        }
        fetchData();
    }, []);

    return (
        <div>
            <h2>Dynamic Chart</h2>
            <Bar data={chartData} />
        </div>
    );
}
This is the Next.js functional component DynamicChartComponent which will visualize the data pulled from an API endpoint. Upon mounting, it fetches data and transforms it into the format expected by Chart.js. Finally, it renders a bar chart using the fetched data.
import Head from 'next/head';
import DynamicChartComponent from '../components/DynamicChartComponent';

export default function Home() {
  return (
    <div>
      <Head>
        <title>Next.js Chart.js Example</title>
        <meta name='description' content='Integration of Chart.js with Next.js' />
        <link rel='icon' href='/favicon.ico' />
      </Head>

      {/* Render the DynamicChartComponent */}
      <DynamicChartComponent />
    </div>
  );
}
This Next.js page component imports and includes the DynamicChartComponent on the page, wrapped within Head tags for page metadata.