Skip to content

Instantly share code, notes, and snippets.

@bmsterling-dandy
Created June 26, 2025 19:59
Show Gist options
  • Select an option

  • Save bmsterling-dandy/363379d381c641f0b05751d381fcb262 to your computer and use it in GitHub Desktop.

Select an option

Save bmsterling-dandy/363379d381c641f0b05751d381fcb262 to your computer and use it in GitHub Desktop.

To provide a deep review and analysis of the Chart.js documentation at https://www.chartjs.org/docs/latest/ and outline the most up-to-date method for setting up Chart.js in a React application with Storybook integration, I’ve thoroughly examined the official Chart.js documentation and relevant resources. Below, I’ll cover the key aspects of the Chart.js documentation, focusing on its structure, features, and setup instructions, followed by a detailed guide on integrating Chart.js with React and Storybook using the latest best practices as of June 2025. The setup will leverage the react-chartjs-2 library, which is the standard for React integration, and Storybook for component visualization.


Deep Review and Analysis of Chart.js Documentation (https://www.chartjs.org/docs/latest/)

The Chart.js documentation, updated as of June 14, 2025, is a comprehensive resource for developers looking to implement dynamic, customizable charts in JavaScript-based applications. Below is an analysis of its key sections, strengths, and areas for improvement, with a focus on its relevance to React and Storybook integration.

1. Overview and Structure

  • Purpose and Scope: Chart.js is an open-source JavaScript library designed for creating responsive, animated, and customizable charts. It supports a variety of chart types (e.g., line, bar, pie, doughnut, radar) and is widely used for data visualization in web applications. The documentation serves as a guide for installation, configuration, and customization, catering to both beginners and advanced developers.
  • Structure: The documentation is organized into clear sections:
    • Getting Started: Covers installation methods (npm, CDN, GitHub) and basic setup for creating a chart.
    • Chart Types: Details supported chart types, including line, bar, pie, doughnut, scatter, and more, with examples of configuration options.
    • Configuration: Explains global and chart-specific options for styling, animations, legends, tooltips, and responsiveness.
    • Integration: Provides guidance on integrating Chart.js with plain JavaScript or module loaders like ES modules and CommonJS.
    • Plugins and Extensions: Describes how to extend Chart.js with custom plugins or use community plugins for additional functionality.
    • Advanced Topics: Includes tree-shaking, performance optimization, and accessibility considerations.
  • Navigation and Usability: The documentation features a clean, sidebar-based navigation with searchable content, making it easy to find specific topics. Code snippets are well-formatted with syntax highlighting, and live examples (via CodePen) enhance understanding.

2. Key Features and Strengths

  • Comprehensive Chart Types: Chart.js supports a wide range of chart types, with detailed configuration options for each. For example, the pie and doughnut charts are highlighted as commonly used, with proportional segment arcs for data visualization.
  • Customization: The documentation emphasizes extensive customization options, such as styling (colors, fonts), animations, and interaction features (tooltips, hover effects). The configuration section is particularly robust, covering global settings, scales, and plugins.
  • Ease of Installation: Chart.js can be installed via npm (npm install chart.js), CDN, or by building from the GitHub repository. The documentation provides clear instructions for each method, including tree-shaking for optimized bundle sizes.
  • Integration with Frameworks: The integration section outlines how to use Chart.js with various environments, though it lacks specific React examples. It mentions compatibility with module loaders, which is relevant for React setups.
  • Community and Ecosystem: Chart.js has a strong community, with plugins like chartjs-plugin-datalabels and chartjs-plugin-annotation extending functionality. The documentation links to these resources, though finding them requires navigation to the plugins section.
  • Responsive Design: Charts are responsive by default, with options to customize responsiveness (e.g., maintainAspectRatio) and handle window resizing, though some React-specific resizing issues are noted in community discussions.

3. Weaknesses and Gaps

  • Limited React-Specific Guidance: While the documentation covers general JavaScript integration, it does not provide detailed examples for React. Developers must rely on external resources or the react-chartjs-2 library documentation for React-specific setups.
  • Storybook Integration: The documentation does not mention Storybook, which is a common tool for React component development. This requires developers to piece together integration steps from other sources.
  • Utils Package Confusion: Some community feedback highlights confusion around the Utils package in Chart.js, which is not well-documented. This can affect developers trying to use helper functions for advanced customizations.
  • Learning Curve for Advanced Features: While the getting started guide is beginner-friendly, advanced topics like custom plugins or complex animations require familiarity with Chart.js internals, which may be challenging without more in-depth examples.

4. Relevance to React and Storybook

  • React Integration: The documentation’s general guidance on module-based setups (e.g., using import Chart from 'chart.js/auto') is applicable to React, but developers need to use react-chartjs-2 for seamless integration. This library wraps Chart.js components for React, simplifying state management and rendering.
  • Storybook: The lack of Storybook-specific guidance means developers must adapt Chart.js components for Storybook manually, focusing on creating reusable, isolated components for visualization in Storybook’s UI.

5. Updates as of June 2025

  • The documentation reflects Chart.js version 4.x, with support for tree-shaking, improved performance, and updated APIs. This ensures compatibility with modern JavaScript ecosystems, including React 18 and the latest Storybook versions (7.x as of 2025).
  • Recent updates emphasize accessibility (e.g., ARIA labels for charts) and modular imports, which align with modern React development practices.

Most Up-to-Date Setup for Chart.js in React and Storybook

To set up Chart.js in a React application with Storybook integration, we’ll use react-chartjs-2 for React compatibility and configure Storybook to display Chart.js components. The following guide is based on the latest Chart.js (v4.x), react-chartjs-2 (v5.x), and Storybook (v7.x) as of June 2025, ensuring compatibility with modern React (v18.x) and a single-page HTML application using CDN-hosted dependencies for simplicity.

Step-by-Step Setup

  1. Create a React Project:

    • Use Vite for a modern, fast setup: npm create vite@latest my-chart-app -- --template react.
    • Navigate to the project directory: cd my-chart-app.
    • Install dependencies: npm install.
  2. Install Chart.js and react-chartjs-2:

    • Install Chart.js and its React wrapper: npm install chart.js react-chartjs-2.
    • Optionally, install plugins like chartjs-plugin-datalabels for additional features: npm install chartjs-plugin-datalabels.
  3. Set Up Storybook:

    • Initialize Storybook: npx storybook@latest init.
    • This sets up Storybook with React support and creates a .storybook directory with configuration files.
  4. Create a Chart Component:

    • Create a reusable React component for a Chart.js chart, such as a bar chart, using react-chartjs-2.
    • Example: A BarChart component that renders a bar chart with customizable data and options.
  5. Configure Storybook:

    • Create a Storybook story for the BarChart component to visualize it in isolation.
    • Ensure Storybook renders the chart correctly with Tailwind CSS for styling (optional but recommended for modern React apps).
  6. Run and Test:

    • Start the React app: npm run dev.
    • Start Storybook: npm run storybook.
    • Verify the chart renders in both the app and Storybook.

Implementation

Below is a complete example of a single-page HTML application using React, react-chartjs-2, and Storybook, served via CDN for simplicity. This includes a bar chart component and its Storybook story. Note that for production environments, you should use a bundler like Vite or Webpack, but this CDN-based approach ensures a standalone, browser-compatible solution.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Chart.js in React with Storybook</title>
  <!-- React and ReactDOM -->
  <script src="https://cdn.jsdelivr.net/npm/react@18.2.0/umd/react.production.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/react-dom@18.2.0/umd/react-dom.production.min.js"></script>
  <!-- Chart.js and react-chartjs-2 -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.4/dist/chart.umd.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/react-chartjs-2@5.2.0/dist/index.umd.min.js"></script>
  <!-- Tailwind CSS for styling -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- Babel for JSX -->
  <script src="https://cdn.jsdelivr.net/npm/@babel/standalone@7.25.6/babel.min.js"></script>
</head>
<body>
  <div id="root" class="p-4"></div>

  <script type="text/babel">
    // Register Chart.js components
    const { Chart, registerables } = window.ChartJS;
    Chart.register(...registerables);

    // BarChart Component
    const BarChart = ({ data, options }) => {
      return (
        <div className="max-w-2xl mx-auto p-4 bg-white shadow-lg rounded-lg">
          <h2 className="text-xl font-bold mb-4">Bar Chart Example</h2>
          <ReactChartJS2.Bar data={data} options={options} />
        </div>
      );
    };

    // Sample Data and Options
    const chartData = {
      labels: ['January', 'February', 'March', 'April', 'May', 'June'],
      datasets: [
        {
          label: 'Sales 2025',
          data: [65, 59, 80, 81, 56, 55],
          backgroundColor: 'rgba(75, 192, 192, 0.2)',
          borderColor: 'rgba(75, 192, 192, 1)',
          borderWidth: 1,
        },
      ],
    };

    const chartOptions = {
      responsive: true,
      plugins: {
        legend: {
          position: 'top',
        },
        title: {
          display: true,
          text: 'Monthly Sales Data',
        },
      },
      scales: {
        y: {
          beginAtZero: true,
        },
      },
    };

    // Render the App
    const App = () => {
      return (
        <div className="min-h-screen bg-gray-100 flex items-center justify-center">
          <BarChart data={chartData} options={chartOptions} />
        </div>
      );
    };

    // Render to DOM
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(<App />);
  </script>
</body>
</html>

Storybook Configuration

To integrate the BarChart component with Storybook, create a story file in your React project. Assuming a Vite-based React project with Storybook initialized, follow these steps:

  1. Create a Story File:
    • In the src/stories directory (created by Storybook init), create a file named BarChart.stories.jsx.
import { Bar } from 'react-chartjs-2';
import { Chart as ChartJS, registerables } from 'chart.js';

// Register Chart.js components
ChartJS.register(...registerables);

// BarChart Component
const BarChart = ({ data, options }) => {
  return (
    <div className="max-w-2xl mx-auto p-4 bg-white shadow-lg rounded-lg">
      <h2 className="text-xl font-bold mb-4">Bar Chart Example</h2>
      <Bar data={data} options={options} />
    </div>
  );
};

// Storybook Meta
export default {
  title: 'Components/BarChart',
  component: BarChart,
  parameters: {
    layout: 'centered',
  },
  argTypes: {
    data: { control: 'object' },
    options: { control: 'object' },
  },
};

// Sample Data and Options
const chartData = {
  labels: ['January', 'February', 'March', 'April', 'May', 'June'],
  datasets: [
    {
      label: 'Sales 2025',
      data: [65, 59, 80, 81, 56, 55],
      backgroundColor: 'rgba(75, 192, 192, 0.2)',
      borderColor: 'rgba(75, 192, 192, 1)',
      borderWidth: 1,
    },
  ],
};

const chartOptions = {
  responsive: true,
  plugins: {
    legend: {
      position: 'top',
    },
    title: {
      display: true,
      text: 'Monthly Sales Data',
    },
  },
  scales: {
    y: {
      beginAtZero:  true,
    },
  },
};

// Default Story
export const Default = {
  args: {
    data: chartData,
    options: chartOptions,
  },
};
  1. Update Storybook Configuration:
    • Ensure .storybook/main.js includes Tailwind CSS and supports JSX files. A typical configuration might look like this:
module.exports = {
  stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'],
  addons: [
    '@storybook/addon-links',
    '@storybook/addon-essentials',
    '@storybook/addon-interactions',
    {
      name: '@storybook/addon-styling',
      options: {
        postCss: {
          implementation: require('postcss'),
        },
      },
    },
  ],
  framework: {
    name: '@storybook/react-vite',
    options: {},
  },
  docs: {
    autodocs: 'tag',
  },
};
  1. Add Tailwind to Storybook:
    • Install Tailwind dependencies: npm install -D tailwindcss postcss autoprefixer.
    • Create a postcss.config.js file:
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
};
  • Create a tailwind.config.js file:
module.exports = { content: ['./src/**/*.{js,jsx,ts,tsx}', './.storybook/**/*.{js,jsx,ts,tsx}'], theme: { extend: {}, }, plugins: [], };
  1. Run Storybook:
    • Start Storybook: npm run storybook.
    • Open http://localhost:6006 to view the BarChart component in Storybook’s UI. The story allows you to interact with the chart’s data and options via Storybook’s controls.

Key Notes for Integration

  • Chart.js Registration: Always register Chart.js components (registerables) to ensure all chart types and plugins are available.
  • Responsive Charts: Use the responsive: true option and consider maintainAspectRatio: false for flexible sizing in React. For resizing issues, ensure the chart is wrapped in a container with defined dimensions, as noted in community discussions.
  • Storybook Best Practices: Use Storybook’s argTypes to make the chart’s data and options props interactive. This allows developers to test different configurations in Storybook’s UI.
  • Tailwind CSS: Tailwind is used for styling the chart container, ensuring a modern, responsive design. Ensure Tailwind is configured in both the React app and Storybook.
  • Performance: Leverage Chart.js’s tree-shaking capabilities by importing only necessary components (e.g., import { Bar } from 'react-chartjs-2') to reduce bundle size.
  • Plugins: For advanced features like data labels, register plugins like chartjs-plugin-datalabels after installing them: ChartJS.register(DatalabelsPlugin).

Running the Application

  • React App: Save the index.html file and open it in a browser to see the bar chart rendered with React and Tailwind styling.
  • Storybook: Run npm run storybook in the project directory to launch Storybook and interact with the BarChart component.

Additional Considerations

  • Accessibility: Add ARIA labels to charts (e.g., aria-label on the canvas element) as recommended in the Chart.js documentation for better accessibility.
  • Testing: Use Storybook’s interaction testing or a library like react-testing-library to test the chart component’s rendering and interactivity.
  • Production: For production, replace the CDN-based approach with a bundler (Vite/Webpack) and optimize the build with tree-shaking. Ensure react-chartjs-2 and Chart.js versions are compatible (e.g., react-chartjs-2@5.x with chart.js@4.x).

Conclusion

The Chart.js documentation (https://www.chartjs.org/docs/latest/) is a robust resource for general JavaScript charting but lacks specific guidance for React and Storybook. By using react-chartjs-2, developers can seamlessly integrate Chart.js into React, and Storybook provides a powerful environment for developing and testing chart components. The provided artifacts (index.html for the app, BarChart.stories.jsx for Storybook, and configuration files) offer a complete, up-to-date setup for June 2025, leveraging Chart.js v4.x, react-chartjs-2 v5.x, and Storybook v7.x. This setup ensures responsive, customizable charts with a modern React workflow and Storybook’s component-driven development approach.

For further details on Chart.js configurations, refer to the official documentation. For react-chartjs-2, check https://react-chartjs-2.js.org/. For Storybook setup, see https://storybook.js.org/docs/react/get-started/install.[](https://www.chartjs.org/docs/)[](https://www.chartjs.org/docs/latest/getting-started/)[](https://www.chartjs.org/docs/latest/getting-started/usage.html)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment