react-chartjs-2

repository·master·Indexed 27 days ago

https://github.com/reactchartjs/react-chartjs-2

React components for Chart.js (version 5.3.1), providing a component-based approach to integrate the Chart.js library into React applications. It includes specialized type-safe components such as Line, Bar, Radar, Doughnut, PolarArea, Bubble, Pie, and Scatter, as well as a generic Chart component. The library provides utility functions for chart events and allows access to the underlying Chart.js instance and canvas context via refs.

Tokens
6.2K
Snippets
39
Records
47
Agent score
91%

What's inside react-chartjs-2

  1. Quickstart: Use react-chartjs-2 components

    master

    To use a component, you must first import the necessary elements from chart.js and register them using ChartJS.register(). Then, import the specific chart component from react-chartjs-2 and pass the required data prop.

    import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";
    import { Doughnut } from "react-chartjs-2";
    
    ChartJS.register(ArcElement, Tooltip, Legend);
    
    <Doughnut data={...} />
  2. Use the Doughnut component

    master

    To render a doughnut chart, import the Doughnut component from react-chartjs-2. You must provide a data object and can optionally provide an options object to customize the chart's behavior and appearance. The component also accepts all standard HTML <canvas> props.

    import { Doughnut } from 'react-chartjs-2';
    
    <Doughnut
      options={...}
      data={...}
      {...props}
    />
  3. Use TypeScript with react-chartjs-2

    master

    While react-chartjs-2 provides robust type inference, you may occasionally need to explicitly define types for the data and options props. To do this, import the necessary types directly from chart.js and pass the specific chart type as a generic argument to ensure type safety and autocompletion.

    Supported ChartType values for generics include:

    • 'bar'
    • 'line'
    • 'scatter'
    • 'bubble'
    • 'pie'
    • 'doughnut'
    • 'polarArea'
    • 'radar'
    import type { ChartData, ChartOptions } from 'chart.js';
    
    interface LineProps {
      options: ChartOptions<'line'>;
      data: ChartData<'line'>;
    }
  4. Handle click events in v4

    master

    The props getDatasetAtEvent, getElementAtEvent, and getElementsAtEvent were removed in v4. To access event data, use the onClick prop and call the tree-shakable methods from chart.js using the chart instance obtained via a ref.

    const chartRef = useRef(null);
    
    <Chart
      ref={chartRef}
      type='bar'
      data={chartData}
      onClick={(event) => {
        const dataset = getDatasetAtEvent(chartRef.current, event);
        const element = getElementAtEvent(chartRef.current, event);
        const elements = getElementsAtEvent(chartRef.current, event);
      }}
    />