admin管理员组

文章数量:1336616

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

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

Share Improve this question edited Mar 11, 2020 at 9:36 asked Mar 11, 2020 at 5:43 user11543110user11543110
Add a ment  | 

3 Answers 3

Reset to default 4 +100

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./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

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.

For making the labels clickable, In the chartEvents which is passed as props under Charts

 <Chart 
  chartEvents = {**chartEvents**}
  rootProps={{ 'data-testid': '3' }}  
/>

Use can pass this as chartEvents

    const chartEvents = [
  {
    eventName: "select",
    callback({ chartWrapper }) {
      console.log("Selected ", chartWrapper.getChart().Ufa.Ei);
    }
  }
];

This will return the label name for for the chart on which u have clicked

working example

本文标签: javascriptHow to make reactgoogle Chart label clickableStack Overflow