How to make react-google Chart label clickable

谁说胖子不能爱 提交于 2020-03-18 05:33:12

问题


I am working on react google-chart react-google-chart and it is working fine. What I want to do is to add click event to the labels of horizontal axis and get the label name and do what ever I want to do

I have google a lot but haven't found a correct solution

What I have done is this

import React, { Component } from 'react'
import { Chart } from "react-google-charts";
export default class manpowerGraph extends Component {
    render() {
     const data=[
        ['Year', 'Sales'],
        ['jan', 20],
        ['feb', 100],
        ['march', 55],
        ['april', 120],
        ['may', 200],
        ['june', 220],


      ]
     const options={
        // Material design options
        chart: {
          title: 'Manpower',
        },
      }
        return (
            <div className="manpowerChart">
<Chart
  chartType="Bar"
  width="100%"
  height="400px"
  data={data}
  options={options}
  legendToggle
  chartEvents={[
    {
      eventName: "ready",
      callback: ({ chartWrapper, google }) => {
        const chart = chartWrapper.getChart();
        google.visualization.events.addListener(chart, "onmouseover", e => {
          const { row, column } = e;
          console.warn("MOUSE OVER ", { row, column });
        });
        google.visualization.events.addListener(chart, "onmouseout", e => {
          const { row, column } = e;
          console.warn("MOUSE OUT ", { row, column });
        });
      }
    }
  ]}
/>

            </div>
        )
}
}

Working code Working code I want when user click on month label it should fire any event or console

I have found this with Javascript with Javascript


回答1:


Change the chart type to ColumnChart and then add the click handler from ready handler.

        <Chart
          chartType="ColumnChart"
          width="80%"
          height="400px"
          data={data}
          options={options}
          legendToggle
          chartEvents={[
            {
              eventName: "ready",
              callback: ({ chartWrapper, google }) => {
                const chart = chartWrapper.getChart();
                var handler = function(e) {
                  console.log(e);
                  var parts = e.targetID.split("#");
                  if (parts.indexOf("label") >= 0) {
                    let idx = parts[parts.indexOf("label") + 1];
                    idx = parseInt(idx);
                    alert(data[idx + 1][0]);
                  }
                };
                google.visualization.events.addListener(
                  chartWrapper.getChart(),
                  "click",
                  handler
                );
              }
            }
          ]}
        />

https://codesandbox.io/s/react-google-charts-columnchart-with-click-handler-cqe1l

Edit

To answer additional questions:

You can do limited styling of x-axis labels by setting hAxis.textStyle in options, supported styling options can be found here https://developers.google.com/docs/api/reference/rest/v1/documents#TextStyle . However, you can not set cursor using textStyle.

You can not style svg through external css. But you can add style tag inside svg tag. Again, not all css styles work, but fortunately, cursor does work.

One crude way of adding style inside svg is to grab the svg element using document.querySelector and then add style as child. This can be done from your ready handler as svg element has been created by the time ready event is fired.

Updated code now looks like:

import React from "react";
import ReactDOM from "react-dom";
import Chart from "react-google-charts";
const data = [
  ["Year", "Sales"],
  ["2004", 1000],
  ["2005", 1170],
  ["2006", 660],
  ["2008", 1030],
  ["2009", 1000],
  ["2010", 1170],
  ["2011", 660],
  ["2012", 1030]
];
const options = {
  title: "Company Performance",
  curveType: "function",
  legend: { position: "bottom" },
  enableInteractivity: true,
  hAxis: { textStyle: { color: "blue", underline: true } }
};
class App extends React.Component {
  render() {
    return (
      <div className="App">
        <Chart
          chartType="ColumnChart"
          width="80%"
          height="400px"
          data={data}
          options={options}
          legendToggle
          chartEvents={[
            {
              eventName: "ready",
              callback: ({ chartWrapper, google }) => {
                let svg = document.querySelector("svg");
                let styles = 'text[text-anchor="middle"] { cursor: pointer; }';
                var css = document.createElement("style");
                if (css.styleSheet) {
                  css.styleSheet.cssText = styles;
                } else {
                  css.appendChild(document.createTextNode(styles));
                }
                svg.appendChild(css);

                const chart = chartWrapper.getChart();
                var handler = function(e) {
                  console.log(e);
                  var parts = e.targetID.split("#");
                  if (parts.indexOf("label") >= 0) {
                    let idx = parts[parts.indexOf("label") + 1];
                    idx = parseInt(idx);
                    alert(data[idx + 1][0]);
                  }
                };
                google.visualization.events.addListener(
                  chartWrapper.getChart(),
                  "click",
                  handler
                );
              }
            }
          ]}
        />
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Working sandbox: https://codesandbox.io/s/react-google-charts-columnchart-with-click-handler-k6fv2




回答2:


It seems that what is available at the moment for clickable tool tips in react-google-charts is limited.

However in order to configure clickable tooltips for react requires you to set the tooltip option like this:

tooltip: { isHtml: true, trigger: "selection" }

(so that it stays shown when you click), and you have setup a select chartEvent event as follows:

  chartEvents={[
        {
          eventName: "select",
          callback: ({ chartWrapper, google }) => {
            var selection = chartWrapper.getChart().setAction({
              id: "alertAction",
              text: "Click Me!",
              action: function() {
                alert("Stay away Corona Virus!!");
              }
            });
            console.warn(selection);
          }
        }
      ]}

See my codesandbox here.

And here's some google documentation on setAction() function, just the way I coded it in my example. Addtionally, there are the getAction() and removeAction() functions that tie into chart tooltips found on that same documentation page.

Hopefully this helps you some.



来源:https://stackoverflow.com/questions/60629886/how-to-make-react-google-chart-label-clickable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!