Skip to content

Instantly share code, notes, and snippets.

@senthilmpro
Created January 11, 2020 19:37
Show Gist options
  • Save senthilmpro/e4124b7037e71e7ae729dde655c76e2b to your computer and use it in GitHub Desktop.
Save senthilmpro/e4124b7037e71e7ae729dde655c76e2b to your computer and use it in GitHub Desktop.
Pie-Chart-React-Hook.js
import React from 'react';
import * as d3 from 'd3';
export const PieChart = (props) => {
const chart = React.useRef();
const { width, height, margin, chartData, title } = props;
// init all d3-chart related data here.
const renderChart = () => {
let radius = Math.min(width, height) / 2 - margin;
// select d3 chart using "useRef" instance
let svg = d3.select(chart.current)
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', "translate(" + width / 2 + "," + height / 2 + ")");
// set dummy data
let data = chartData;
let colors = ['#32a852', '#36d3ff', '#ffff36', '#ff5959', '#f159ff'];
let colors2 = ["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56"];
// set the color scale
let color = d3.scaleOrdinal()
.domain(data)
.range(colors);
let pie = d3.pie()
.value(function (d) { return d.value; });
let data_ready = pie(d3.entries(data));
svg
.selectAll('whatever')
.data(data_ready)
.enter()
.append('path')
.attr('d', d3.arc()
.innerRadius(0)
.outerRadius(radius)
)
.attr('fill', function (d) { return (color(d.data.key)) })
.attr("stroke", "black")
.style("stroke-width", "2px")
.style("opacity", 0.7);
}
React.useEffect(() => {
renderChart();
}, [])
// return chart
return (
<div className="piechart_container">
{title && <div className="piechart_title">{title}</div>}
<svg width={width} height={height} ref={chart} />
</div>
)
}
PieChart.defaultProps = {
width: 450,
height: 450,
margin: 40,
title: 'My Pie Chart',
chartData: { a: 9, b: 20, c: 30, d: 8, e: 12 }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment