reactjs / react-chartjs

common react charting components using chart.js
MIT License
2.93k stars 301 forks source link

generateLegend prop not working #19

Closed adamellsworth closed 9 years ago

adamellsworth commented 9 years ago

I'm not able to create a legend via the generateLegend prop. From the examples I see on stackoverflow, it looks like the legend needs its own div, so applying it directly to the this.state.chart[name] via the following function may not be working:

https://github.com/jhudson8/react-chartjs/blob/master/lib/core.js#L21

Here's my markup:

<LineChart data={chartData} options={chartOptions} redraw generateLegend />

Edit: here's an example with the chart and legends in their own divs: http://jsfiddle.net/vrwjfg9z/

temnoregg commented 9 years ago

I think it is not working like this... you have to call generateLegend() over the graph reference to get the legend...

That's why I ended with separate Legend component like this:

  var ChartLegend = React.createClass({
    propTypes: {
      datasets: React.PropTypes.array.isRequired
    },

    render: function () {
      var datasets = _.map(this.props.datasets, function (ds) { 
        return <li><span className="legend-color-box" style={{ backgroundColor: ds.strokeColor }}></span> { ds.label }</li>;
      });

      return (
        <ul className={ this.props.title + "-legend" }>
          { datasets }
        </ul>
      );
    }
  });
jhudson8 commented 9 years ago

looks like this was answered. thanks @temnoregg

framerate commented 9 years ago

Can someone please clarify this? @temnoregg @jhudson8

you have to call generateLegend() over the graph reference to get the legend...

I don't follow what you mean. I can't seem to find any documentation on the legend stuff

temnoregg commented 9 years ago

I mean like this

var ChartWithLegend = React.createClass({
  componentDidMount: function () {
    var legend = this.refs.chart.getChart().generateLegend();

    this.setState({
      legend: legend
    });
  },
  render: function () {
    var legend = this.state && this.state.legend || '';

    return (
      <div>
        <LineChart ref="chart" {...this.props} />
        <div dangerouslySetInnerHTML={{ __html: legend }} />
      </div>
    );
  }
});
randichilyon commented 8 years ago

i still don't understand how to add the legend to my chart.. can anyone explain further about this :(

wrk123 commented 7 years ago

@christchron I was also facing the issue, but after some experimentation I found that you need to attach the solution mentioned by @temnoregg as a separate component along with passing it chart data, no option value, then you will get the required legend alongwith graph. Was experimenting the same with Piechart. @temnoregg hot to get legend with values plotted in the graph or how to display the values in the graph ?