avatar

ShīnChvën ✨

Effective Accelerationism

Powered by Druid

AntV F2 with React

Fri Jun 09 2023

AntV is open source data visualization library developed by Alibaba Ant Group. It provides a set of powerful yet easy to use data visualization solutions, including G2, G6, F2 and L7.

F2 is a mobile-friendly, interactive and flexible charting library. It is dedicated to providing a simple, convenient and friendly data visualization solution for mobile phones.

The chart can be written in a declarative approach using JSX syntax, which not only makes the code more intuitive and concise, but also allows for easy integration with frameworks such as React and Vue.

Here I will show you how to use F2 with React.

Installation

npm install @antv/f2 --save

Usage

The library basically draws a chart on a canvas element. So the way to use it is to put a canvas element in a React component, then draw the chart by calling F2's API.

import { Axis, Canvas, Chart, Line, Tooltip } from '@antv/f2';

// Define the type of data that will be used in the chart
type ChartData = {
    date: string;     // date as x axis
    value: number;    // value as y axis
}

/**
 * Function to render the chart
 * @param data The data to be used in the chart
 * @param canvasId The id of the canvas element
 */
const renderChart = (data: ChartData[], canvasId: string) => {
    // Get the canvas context
    // @ts-ignore
    const context = document?.getElementById(canvasId)?.getContext('2d');

    // Define the chart using JSX syntax
    const { props } = (
        <Canvas context={context} pixelRatio={window.devicePixelRatio}>
            <Chart data={data}>
                <Axis
                    field="date"
                    tickCount={3}
                    style={{
                        label: { align: 'between' },
                    }}
                />
                <Axis field="value" tickCount={5} />
                <Line x="date" y="value" shape="smooth" />
                <Tooltip />
            </Chart>
        </Canvas>
    );

    // Create a new chart instance and render it
    const chart = new Canvas(props);
    chart.render();
}

// React component that renders the chart
const MyChart: React.FC<{ chartData: ChartData[]; chartId: string }> = ({ chartData, chartId }) => {

    // Render the chart when the chartData prop changes
    useEffect(() => {
        renderChart(chartData, chartId);
    }, [chartData]);

    // Render the canvas element
    return <div>
        <canvas id={chartId}></canvas>
    </div>
}