React Charts

repository·beta·Indexed 11 days ago

https://github.com/TanStack/react-charts

A library for creating simple, immersive, and interactive charts in React applications, powered by D3. It supports line, bar, column, bubble, and area charts through a flexible, declarative API. Note: This project is no longer actively maintained. Version 1.0.0-semantic-release requires React v16.8+ and is compatible with react-dom.

Tokens
6.9K
Snippets
21
Records
30
Agent score
83%

What's inside React Charts

  1. Overview of React Charts features

    beta

    React Charts provides simple, immersive, and interactive charts for React applications. It is declaratively powered by D3 and is designed to be hyper-responsive.

    Supported Chart Types:

    • Line Charts
    • Bar Charts
    • Column Charts
    • Bubble Charts
    • Area Charts

    Key Capabilities:

    • Axis Stacking
    • Inverted Axes
    • Multiple Axes
    • Declarative API
  2. Overview of React Charts capabilities

    beta

    React Charts is a React component designed for rendering various types of X/Y charts. It abstracts away the complexities of SVG and D3, allowing you to focus on data and styling rather than low-level graphics implementation.

    Supported chart variations include, but are not limited to:

    • Line charts
    • Area charts
    • Bar charts
    • Column charts
    • Bubble charts
  3. Configure Axes and Scale Types

    beta

    Axes are required components. You must provide a primaryAxis and at least one axis in the secondaryAxes array. Axes use a getValue function to extract values from your datums.

    Available Scale Types

    Scale TypeDescriptionBest Use Case
    linearContinuous numerical scale.Primary or Secondary axis.
    bandBanded/categorical scale.Primary axis for bar charts.
    timeContinuous UTC Date scale.Primary axis.
    timeLocalContinuous localized Date scale.Primary axis.
    logLogarithmic numerical scale.Secondary axis.

    Customizing Curves

    For element types that support lines (like line or area), you can pass a D3 curve generator function to the curve property in AxisOptions (e.g., curve: d3.curveMonotoneX).

    type MyDatum = { date: Date, stars: number }
    
    const primaryAxis = React.useMemo(
      (): AxisOptions<MyDatum> => ({
        getValue: datum => datum.date,
      }),
      []
    )
    
    const secondaryAxes = React.useMemo(
      (): AxisOptions<MyDatum>[] => [
        {
          getValue: datum => datum.stars,
        },
      ],
      []
    )
  4. Define data structures for React Charts

    beta

    React Charts uses a Series structure to organize data. A Series consists of a label and a data array. The elements within the data array are your custom data objects (often referred to as Datums).

    Example structure:

    type DailyStars = {
      date: Date,
      stars: number,
    }
    
    type Series = {
      label: string,
      data: DailyStars[]
    }
    
    const data: Series[] = [
      {
        label: 'React Charts',
        data: [
          {
            date: new Date(),
            stars: 202123,
          }
        ]
      }
    ]
    type DailyStars = {
      date: Date,
      stars: number,
    }
    
    type Series = {
      label: string,
      data: DailyStars[]
    }
    
    const data: Series[] = [
      {
        label: 'React Charts',
        data: [
          {
            date: new Date(),
            stars: 202123,
          }
          // ...
        ]
      },
      {
        label: 'React Query',
        data: [
          {
            date: new Date(),
            stars: 10234230,
          }
          // ...
        ]
      }
    ]
  5. Prerequisites for using React Charts

    beta

    To use React Charts effectively, you should have a solid understanding of your data structure.

    While not strictly required for basic charting, a productive workflow involves understanding high-level Scale Archetypes. You do not need to know how to build scales or use d3-scale directly, but understanding the conceptual differences between these types will help you choose the right configuration:

    • time scales
    • linear / continuous scales
    • ordinal / band scales
  6. Understand the React Charts data model

    beta

    React Charts expects data in an array of series, where each series contains an array of datums.

    Each datum object can have any property names, but by convention, one property is used for the primaryAxis and others for secondaryAxes. When using TypeScript, you should pass your datum type as a generic to the axis options to ensure type safety.

    Data Structure Example:

    const data = [
      {
        label: 'Series Name',
        data: [
          { primary: '2022-01-01', value: 100 },
          { primary: '2022-01-02', value: 150 },
        ],
      },
    ];
    const data = [
      {
        label: 'Purchases',
        data: [
          {
            date: new Date(),
            stars: 299320,
          },
        ],
      },
    ];
  7. Memoize props for React Charts to prevent infinite loops

    beta

    The <Chart> component requires several options to be stable. You must memoize these options using React.useMemo or React.useCallback. Failing to do so can cause infinite change-detection loops or severe performance degradation. This applies to data, primaryAxis, and secondaryAxes.

    const data = React.useMemo(() => [
      {
        label: 'Series 1',
        data: [
          // ...
        ],
      },
    ], []);
    
    const primaryAxis = React.useMemo(() => ({
      getValue: (datum: MyDatum) => datum.date,
    }), []);
    
    const secondaryAxes = React.useMemo(() => [
      {
        getValue: (datum: MyDatum) => datum.value,
      },
    ], []);
  8. Minimum configuration to render a chart

    beta

    To render a basic chart in React Charts, you need to provide three main pieces of information in the options prop of the <Chart /> component:

    1. An array of Series objects: Each series must have a label (string) and a data property. The data property is an array of Datums (objects representing your data points).
    2. primaryAxis: An AxisOptions object that defines how to access the primary value from your data (e.g., the X-axis value).
    3. secondaryAxes: An array of AxisOptions objects that define how to access values for the Y-axes (e.g., the values being plotted).

    Both axes require a getValue function that takes a datum and returns the specific value to be used on that axis.

    function App() {
      const primaryAxis = React.useMemo(
        (): AxisOptions<DailyStars> => ({
          getValue: datum => datum.date,
        }),
        []
      )
    
      const secondaryAxes = React.useMemo(
        (): AxisOptions<DailyStars>[] => [
          {
            getValue: datum => datum.stars,
          },
        ],
        []
      )
    
      return (
        <Chart
          options={{
            data,
            primaryAxis,
            secondaryAxes,
          }}
        />
      )
    }
  9. Configure environment variables for React Charts docs

    beta

    To run the documentation locally, you must provide Notion credentials in your .env and .env.build files. Rename the sample files and update the following keys:

    • NOTION_TOKEN: Your Notion integration token.
    • BLOG_INDEX_ID: Your specific blog index ID.
    -NOTION_TOKEN=XXXX
    +NOTION_TOKEN=<YOUR_TOKEN>
    -BLOG_INDEX_ID=XXXXX
    +BLOG_INDEX_ID=<YOUR_BLOG_INDEX_ID>
  10. Quick Start with React Charts

    beta

    To render a basic chart in React, use the Chart component from react-charts. You must provide two primary props:

    1. data: An array of series objects. Each object contains a label and a data array of coordinate pairs (e.g., [x, y]).
    2. axes: An array of axis configurations. Each axis object defines its type (e.g., 'linear'), position (e.g., 'bottom', 'left'), and whether it is the primary axis.

    The Chart component is hyper-responsive and will automatically fill the available space of its parent container. Ensure the parent element has defined dimensions (width and height) via CSS or inline styles.

    import React from 'react'
    import { Chart } from 'react-charts'
    
    function MyChart() {
      const data = React.useMemo(
        () => [
          {
            label: 'Series 1',
            data: [
              [0, 1],
              [1, 2],
              [2, 4],
              [3, 2],
              [4, 7],
            ],
          },
          {
            label: 'Series 2',
            data: [
              [0, 3],
              [1, 1],
              [2, 5],
              [3, 6],
              [4, 4],
            ],
          },
        ],
        []
      )
    
      const axes = React.useMemo(
        () => [
          { primary: true, type: 'linear', position: 'bottom' },
          { type: 'linear', position: 'left' },
        ],
        []
      )
    
      return (
        <div
          style={{
            width: '400px',
            height: '300px',
          }}
        >
          <Chart data={data} axes={axes} />
        </div>
      )
    }