Giter Site home page Giter Site logo

rakannimer / react-google-charts Goto Github PK

View Code? Open in Web Editor NEW
1.6K 28.0 334.0 9.92 MB

A thin, typed, React wrapper over Google Charts Visualization and Charts API.

Home Page: https://react-google-charts.com/

License: MIT License

TypeScript 64.39% JavaScript 5.70% CSS 0.28% MDX 29.63%
react google-charts charts react-google-charts area-chart bar-chart bubble-chart calendar-chart candlestick-chart column-chart

react-google-charts's Introduction

React Google Charts

Logo

A thin, typed, React wrapper for Google Charts.

version downloads license bundle size


Quickstart   •   Docs   •   Contributing   •   Stack Overflow

Quickstart

Install this library with your favorite package manager:

yarn add react-google-charts

or

npm install --save react-google-charts

Then, import and use it:

import { Chart } from "react-google-charts";

<Chart
  chartType="ScatterChart"
  data={[["Age", "Weight"], [4, 5.5], [8, 12]]}
  width="100%"
  height="400px"
  legendToggle
/>

Docs

You can also check this step-by-step tutorial that will walk you through the creation of a full-fledged dashboard with this library.

Contributing

Contributions are very welcome. Check out CONTRIBUTING.md

Run the Storybook

git clone https://www.github.com/rakannimer/react-google-charts
cd react-google-charts
yarn
yarn start:storybook

react-google-charts's People

Contributors

aalises avatar alexfqc avatar andrewda avatar bcbrian avatar berndverhofstadt avatar brianjfeldman avatar charleschenster avatar dangreen avatar dependabot[bot] avatar duanefields avatar dvdplm avatar dvemac avatar evilfer avatar fabriciocolombo avatar fiatexodus avatar hozefaj avatar igorlukanin avatar jacaetevha avatar jadjoubran avatar jimulle avatar kaitlynreese avatar kirananto avatar kmayer avatar lgo avatar marcin1j avatar newsiberian avatar oracprime avatar rakannimer avatar taylorham avatar theel0ja avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-google-charts's Issues

Script.js dependency breaks Mocha tests

When I include react-google-charts on a component my mocha tests are breaking:

TypeError: doc.getElementsByTagName is not a function
 at .../node_modules/react-google-charts/node_modules/scriptjs/dist/script.js:13:18

The Script.js library appears to expect a document to exist during execution, but that is not the case when running mocha tests.

Document is not defined error

I'm getting the following error:

ReferenceError: document is not defined
[1]     at /my/project/node_modules/scriptjs/dist/script.js:12:13
[1]     at doc (/my/project/node_modules/scriptjs/dist/script.js:8:72)

In case you need some context, I'm using it within this boilerplate.

Evidently something is wrong because document is not defined on the server. Is this scriptjs's fault? Any quick fixes?

Can't use it with Browserify and an isomorphic React app

It give me this error

var doc = document
  ^

  ReferenceError: document is not defined
at /Users/mboutin2/working-directory/project/node_modules/scriptjs/dist/script.js:12:13
at doc (/Users/mboutin2/working-directory/project/node_modules/scriptjs/dist/script.js:8:72)
at Object.<anonymous> (/Users/mboutin2/working-directory/project/node_modules/scriptjs/dist/script.js:11:3)
at Module._compile (module.js:413:34)
at Module._extensions..js (module.js:422:10)
at Object.require.extensions.(anonymous function) [as .js] (/Users/mboutin2/working-directory/project/node_modules/babel-register/lib/node.js:166:7)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Module.require (module.js:367:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/Users/mboutin2/working-directory/project/node_modules/react-google-charts/lib/components/GoogleChartLoader.js:16:17)
at Module._compile (module.js:413:34)
at Module._extensions..js (module.js:422:10)
at Object.require.extensions.(anonymous function) [as .js] (/Users/mboutin2/working-directory/project/node_modules/babel-register/lib/node.js:166:7)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)```

Unable to load two charts at once

I'm trying to display two charts at once, Timeline and LineChart, whichever I put as a second chart (bellow the first one) I keep getting error for it "google.load is not a function". If I remove one of the charts, it's working perfectly. I checked the data, is correct. Cause when I'm loading them separately, they are working. Here's a sample of my code:

<FlexRow>
                <Chart chartType="Timeline"
                       graph_id="TimelineChart"
                       chartPackages={['timeline']}
                       rows={this.props.timeline.rows}
                       columns={this.props.timeline.columns}
                       width={"100%"} height={"400px"}/>
</FlexRow>
<FlexRow>
                <Chart chartType="LineChart"
                       rows={this.props.linechart.rows}
                       columns={this.props.linechart.columns}
                       width={"100%"} height={"400px"}/>
</FlexRow> 

What could be the problem?

Sanjay diagram support

Hi Rakan,

Thanks for this very helpful piece of work.
Wondered if Sankey diagram was supported or if you had any plan to add it in the near future?

React 0.14

<Chart chartType="PieChart" options={options} data={data} graph_id={id}/>

Error: Invariant Violation: ReactCompositeComponent.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.

Chart title / axis labels do not update

I have a react component that contains a chart. I want the chart to render different data depending on the state of the component. The change in state represents a change in what should be rendered along the horizontal axis.

When I call setState(...), the ScatterPlot is re-rendered correctly. However, the chart's title and hAxis / vAxis labels do not change to reflect the change in state. I can see in React DevTools that the options prop has updated correctly, but the title and hAxis label are stuck as whatever string was initially rendered.

I'm guessing it is due to the optimization in Chart.js, l.109 - 132. Once wrapper is defined, it never gets re-created; perhaps this is why the title and axis are never re-rendered?

GeoCharts

I'm using this library and lovin' it! It actually works, I can render the charts from the examples.
Now I'm trying to render GeoCharts: https://developers.google.com/chart/interactive/docs/gallery/geochart#core

This is my code:

        var options2 = {
          sizeAxis: { minValue: 0, maxValue: 100 },
          region: '155', // Western Europe
          displayMode: 'markers',
          colorAxis: {colors: ['#e7711c', '#4374e0']} // orange to blue
        };

        var rows2 = [[
          ['Germany', 200],
          ['United States', 300],
          ['Brazil', 400],
          ['Canada', 500],
          ['France', 600],
          ['RU', 700]
        ]];

        var columns2 = [        {
                    'type': 'string',
                    'label' : 'Country'
                },
                {
                    'type' : 'number',
                    'label' : 'Number'
                }];

...
                            <Chart chartType = "GeoChart"
                              rows = {rows2}
                              options = {options2}
                              graph_id = "GeoChart"
                              width={"100%"}
                              height={"400px"}  legend_toggle={false} />

I get an empty div, and no errors.
May this be related to the part where google includes external scripts?

Note: GeoCharts require both of the following lines in the <head> section of the page
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript" src="https://www.google.com/jsapi"></script>

Thanks!

Wanted to say thanks for the work you've done on this. We started using it last year on Cronitor.io at version ~0.12 I think. We moved to 1.0 and i'm digging the richer API.

Broken server render

When i import the react-google-chart the server rendering broken.

"Document is not defined"

How can i use the module without this error?

Cannot render chart from array

Hello,

I am trying to pass data as an array, using the code below. The chart doesn;t appear just a grey box. I don't get any errors, Can you help?

         var chartAttributes = {
            chartType: this.props.chartTypes[this.state.statsChart.chartType],
            graph_id: this.props.chartTypes[this.state.statsChart.chartType],
            width: this.state.statsChart.chartWidth,
            height: this.state.statsChart.chartHeight,
            legend_toggle: true
        };

        chartAttributes.options = {
            title: 'Stats ' + this.props.chartTypes[this.state.statsChart.chartType],
            is3D: this.props.chartTypes[this.state.statsChart.chartType] == 'PieChart'
        };

        chartAttributes.data = [
            ['Attendance','Percentage'],
            ['Present',this.getCodesTotals().present[0]],
            ['Authorised Absent',this.getCodesTotals().authorisedAbsent[0]],
            ['Unauthorised Absent',this.getCodesTotals().unauthorisedAbsent[0]]
        ];

        return (
            <Chart {...chartAttributes} />
        );

Typo in examples

In file examples/src/components/Examples/BarCharts.js here is a typo: var BarChartData = require('../../sample_data/Barchart'); (expect BarChart)

PieCharts

Is there a pie chart example that I can look at anywhere?

warning message when there is no data

Chart with this properties show error message

Data column(s) for axis #0 cannot be of type string

{"chartType":"BarChart","data":[["Element","Density",{"role":"style"}]],"width":"100%","height":"300px","options":{"title":"Density of Precious Metals, in g/cm^3","bar":{"groupWidth":"95%"},"legend":{"position":"none"}},"chartEvents":[{"eventName":"onmouseover"}]}

Initialize from Array does not work

https://github.com/RakanNimer/react-google-charts/blob/master/src/components/Chart.js#L91

drawChart: function() {

        if ((this.props.data !== null && this.props.data.length === 0) || this.props.columns.length === 0) {
            return;
        }
...

The above code means that if we don't specify a columns prop, drawChart exits without doing anything. From what I can tell, this means that the first example in your README where you provide options and data, but no columns, does not display anything.

SetSelection function not working as expected

I added a ref to the chart component and am calling: this.refs.userVisitPieChart.wrapper.getChart().setSelection([{row: 1, column: null}]
It looks like this.refs.userVisitPieChart.wrapper.getChart().setSelection is exposed correctly by the chart wrapper, but the setSelection function with an argument does not augment the Pie Chart as intended.

scriptjs based loader breaks working

0.1.8 worked (jQuery based loader), 0.2.2 gives 'Table has no columns' (no user code changes).

The given datatable is identical, but replacing the contents of the GoogleChartLoader.js component with the jQuery version in 0.1.8 operation is restored.

My project is using React 15.1, jQuery 2.2.4, and is delivered as a single .js bundle using browserify, transform, babelify, and bundle. No errors on the browsers console.

several charts on the same page

Hi,

really interesting wrapper to work with google charts in react.

I'm just curious. I'm not abe to figure out myself, how I add more charts to the same page. It seems, that the chart only works, when there's only one chart on the page.

/BR

Martin

Drawing multiple graphs

Hi there,

Is there a way to create multiple graphs? I can get one graph to render then the second one will be stuck in the Rendering Chart... phase.

I have an array of objects that have configurations/options for the graphs then I map this array to a component that calls <Chart />.

Am I missing something here to make multiple graphs show up? Thanks!

new chartType blows away events

It turns out that changing chart type blows away events. I've had to do this inside drawChart():

...
else {
  this.updateDataTable.bind(this)();
  this.wrapper.setDataTable(this.dataTable);
  // this.wrapper.setChartType(this.props.chartType)
  this.wrapper.setOptions(this.props.options)
  if (this.wrapper.getChartType() != this.props.chartType) {
    google.visualization.events.removeAllListeners(this.wrapper)
    this.wrapper.setChartType(this.props.chartType)
    var self = this
    google.visualization.events.addOneTimeListener(this.wrapper, 'ready', function () {
      self.chart = self.wrapper.getChart();
      self.listenToChartEvents.call(self);
    });
  }
}
this.wrapper.draw();

Gauge isn't working?

Trying to render a gauge and it is not working at all. Not sure what I might be doing incorrectly here.
import React, { Component, PropTypes } from 'react';

  import { Chart } from 'react-google-charts';

  class NetworkGauge extends Component {

    componentDidMount() {
      this.renderChart();
    }

    constructor(props, context) {
      super(props, context);
      this.state = {
        data: [],
        options: {},
      }
    }

    renderChart() {
      const data = [
         ['Label', 'Value'],
         ['Memory', 80],
         ['CPU', 55],
         ['Network', 68]
      ];

      const options = {
         redFrom: 90, redTo: 100,
         yellowFrom:75, yellowTo: 90,
         minorTicks: 5
      };

      this.setState({
         'data' : data,
         'options' : options
      });

    }

    render() {
      console.log(this.state.data);
      return (
        <Chart chartType="Gauge" data ={this.state.data} options={this.state.options} graph_id="Gauge" width={"100%"} height={"400px"}>
        </Chart>
      );
    }
  }

  export default NetworkGauge;

IE9 compatibility

In IE9 the charts display a message like 'Invalid chart type: LineChart' and the console displays: SCRIPT5009: 'gvjs_lk' is undefined

The same code works fine in Chrome.

enabling diff charts

Grist for the mill: I've enabled diff charts by adding the following code to buildDataTableFromProps:

  buildDataTableFromProps() {
    // debug('buildDataTableFromProps', this.props);
    if (this.props.diffdata) {

        let diffdata = this.props.diffdata
        let oldData = google.visualization.arrayToDataTable(diffdata.old)
        let newData = google.visualization.arrayToDataTable(diffdata.new)
        // must take computeDiff from prototypes since not available with charts early in process
        let computeDiff = google.visualization[this.props.chartType].prototype.computeDiff
        let chartDiff = computeDiff(oldData,newData)

        return chartDiff

    }

(and of course adding a diffdata prop)

The key is getting access to the computeDiff method before having access to the chart for the chartType. Grabbing it from the appropriate prototype in the google.visualization access chain seems to work.

Turn off OnClick for chart legend

When i clicked the legend of my chart, it will turn off the line that i clicked. I want to know how to turn off that onclick function, because i edited the tooltip so the column is like:
{type:'datetime', label:'Date', role: 'domain'},
{type: 'number', label:'Chat Count', role: 'data'},
{type: 'string', role: 'tooltip', p: {'html': true}},
{type: 'number', label:'Chat Growth', role: 'data'},
{type: 'string', role: 'tooltip', p: {'html': true}}

when i clicked the legends, i got this error : All series on a given axis must be of the same data type

Using material version of charts.

I'm trying to load the material version of the charts by passing the chartPackages prop. For example, if I set chartPackages to the following:

let chartPackages = ['line'];
....
<Chart chartPackages={chartPackages}....

I get the error google.load is not a function.

A few questions:

  • Can I load the material version of charts using the library ? As the chartPackages prop isn't documented and I found out about it by looking it at the code.
  • Can I update the README.md file with the props that the componenet does accept in order to be some basic level of documentation ?

Cool library, otherwise, thanks!

typescript .d.ts?

Sorry to ask this here; is there a typescript definition file available for react-google-charts?

Timeline Chart

I can't create timeline chart using those configurations. It says React Chart Rendering... then nothing happens, no console error.

<Chart
  chartType="Timeline"
  columns={[{"id":"President","type":"string"},{"id":"Start","type":"number"},{"id":"End","type":"number"}]}
  rows={[["Washington",12,14],["Adams",12,14],["Jefferson",12,14]]}
  graph_id="ScatterChart"
  options={{"width":"600px"}}
  width={"100%"}
  chartPackage={"timeline"}
/>

Customized tooltips on scatter plot not working

I have been able to get them to work outside of react-google-charts, see http://jsfiddle.net/4THAe/1/

I have been stumped by this error while using react-google-charts: "All series on a given axis must be of the same data type". Can you confirm that you can get tooltips working on scatter plots with react-google-charts?

Here is my code, it is as basic as possible:

function build_scatter() {
return {rows: [[0.5, 0.5, 'test123']], columns: [{
        type: 'number',
            role: 'domain',
            label:'Overall Score'
      },
      {
        type: 'number',
            role: 'data',
        label:'QB'
      },
        {
        type: 'string',
            role: 'tooltip',
        label: null
      }
    ]};
}

and then for my plot:

var ScatterChartData =
{
    circle_scatter:
    {
      rows : circle_scatter_data.rows,
      columns : circle_scatter_data.columns,
      options:
      {
        title: 'Overall Score vs. Position',
        legend: {bottom: 'top', textStyle: {color: 'black', fontSize: 12}},
        colors: ['#0000FF','#FF0000', '#00FF00'],
        pointSize: 2,
        vAxis: {title: 'Overall Score'},
      }
    }
};

Upgrade to React 0.14

Looks like the react google charts refers to deprecated methods in React 0.14. Opening an issue to track migration

setChartType for wrapper

I've added setChartType after setOptions (around line 125) to allow for switching of chart types

this.wrapper.setOptions(this.props.options);
this.wrapper.setChartType(this.props.chartType)

any chance you could add this?

Chart.defaultProps.height/width shadows options.height/width

This is the code to compute the div style at https://github.com/RakanNimer/react-google-charts/blob/master/src/components/Chart.js#L273

    const divStyle = {
      height: this.props.height || this.props.options.height,
      width: this.props.width || this.props.options.width,
    };

I assume its purpose is "when this.props.height is absent, fallback to this.props.options.height".

But then we have defaultProps from https://github.com/RakanNimer/react-google-charts/blob/master/src/components/Chart.js#L324 which says

Chart.defaultProps = {
  width: '400px',
  height: '300px',
};

which provides this.props.height already when it's absent, and that || will never take effect unless this.props.height is manually set to null of 0 etc, and leaving height to be always 300px if we set options.height to some value without setting props.height, making the behaviour very confusing

Fetching Data via Data Source

Currently we fetch our data from Google Spreadsheets in a project I am working on. If I were to fetch this data and then pass it to the component, would it be able to accept the response?

I'm not 100% sure how I would go about doing the google.visualization calls.

new google.visualization.Query

perhaps we could pass in a query prop and we could create a function within react-google-charts that would do the fetching and setting of data?

Not rendering, just a empty div

I'm trying to use it, but, inspecting, I'm getting a div without contents:

No browserify errors or console errros.

What can it be?

Forever rendering

I have copied one of the example <Chart />s but I just get the rendering node, the chart never actually renders. Is there a way I can debug this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.