!!!###!!!title=177-How to get the data point information in a click event using react-vchart——VisActor/VChart FAQ documents!!!###!!!

How to get the corresponding data point information in a click event using @visactor/react-vchart?

Question Description

How to implement a bar chart like this example in React using @visactor/react-vchart? How can I bind a click event? Is it possible to retrieve the corresponding data information from the click event?

Solution

The tutorial for using the React wrapper library react-vchart provided by VChart can be referred to. react-vchart supports two types of components:

Code Example

import { VChart, VChartProps } from "@visactor/react-vchart";
import { Component } from "react";

export interface BarChartProps {
  colors?: string[];
  data: any[];
}

export class BarChart extends Component<BarChartProps> {
  state: { active: any } = {
    active: null
  };
  parseSpec = () => {
    const colors = this.props.colors;
    return {
      type: "bar",
      data: [
        {
          id: "barData",
          values: this.props.data
        }
      ],
      xField: "name",
      yField: "value",
      color: {
        type: "ordinal",
        domain: [],
        range: colors
      }
    } as VChartProps["spec"];
  };

  handleClick = (e: any) => {
    this.setState({ active: e.datum });
  };

  render() {
    return (
      <>
        <p>{`active bar: ${this.state.active?.name ?? ""}`}</p>
        <VChart spec={this.parseSpec()} onClick={this.handleClick} />
      </>
    );
  }
}

Results