Chartjs-React-chart does not render the legend for PIE chart

1👍

Found the issue and posting the solution for the same.

Issue – The issue is within the version of react-chart available on npm. The latest version available there is 0.6.0 whereas github repo have 0.7.3. The issue is here react-chart. The snippet in 0.6.0 is as follows

classData[name] = function() {
   return this.state.chart[type].apply(this.state.chart, arguments);
};

Please see the code which I used to display legend after getting latest version.

Component File

componentDidUpdate(){
   var pieChartLegend = this.refs.pieChart && this.refs.pieChart.generateLegend();
   if(this.state.chartLegend !== pieChartLegend){this.setState({chartLegend:pieChartLegend});}
}

render(){
   return(
    <div>
    <PieChart ref="pieChart" data={data} style={{height:'60%',width:'100%'}}
    options={
        {
            tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value + ' %' %>",
            legendTemplate:"<ul class=\"<%=name.toLowerCase()%>-legend\" style=\"list-style-type: none\"><% for (var i=0; i<segments.length; i++){%><li style=\"text-align: left;\"><span style=\"color:<%=segments[i].fillColor%>\"><%if(segments[i].label){%><%=segments[i].label%><%}%></span></li><%}%></ul>"
        }
    } />
    <div style={{position:'absolute',top:'100px',left:'370px'}} dangerouslySetInnerHTML={{__html: this.state.chartLegend}} />
    </div>
    )
}

Leave a comment