7

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

3 Answers3

4

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

ckedar
  • 1,859
  • 4
  • 7
  • Hey thats cool, but how ca I add style to those labels so to make it look like link, How can I add External style? –  Mar 16 '20 at 03:56
  • Add ` hAxis: {textStyle: {color:"blue", "underline":true}}` to options. See updated sandbox: https://codesandbox.io/s/react-google-charts-columnchart-with-click-handler-298hn – ckedar Mar 16 '20 at 06:41
  • Is there any documentation for styling like you are doing for underline I have to add several style like cursor:'pointer' and many more, could you help me with any documentations –  Mar 16 '20 at 07:26
  • After a lot of search I could finally locate the documentation: https://developers.google.com/docs/api/reference/rest/v1/documents#TextStyle However, this does not have option like cursor that you are looking for. – ckedar Mar 16 '20 at 08:18
  • So how can I change cursor please help me out once –  Mar 16 '20 at 08:20
  • hey sir could you please help me here https://stackoverflow.com/questions/61039619/react-google-chart-not-taking-up-the-options I am stuck here for so long now please check one whenever you are free – manish thakur Apr 07 '20 at 19:02
0

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.

EspressoBeans
  • 1,747
  • 12
  • 22
  • Hey I have found this kind of example which is working on click of graph columns, what I want is to add click event on the labels i.e jan,feb etc and in your code 2011,2012 which are years I want to add click event on labels. the above code is not gona help me – manish thakur Mar 15 '20 at 06:13
0

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