How to create a pie chart in React
Overview
Building charts in React can be complex and daunting. However, there is a lightweight library that can help us build charts quickly in no time.
In this shot, we'll be using the react-minimal-pie-chart package to create charts and customize them using various libraries to make them look professional.
Here's what we've to do:
- Use
create-react-appto start and create our React app. - Install the
minimal-pie-chartusingnpm i react-minimal-pie-chart. - We go to our
app.jsfile and pass various props into the<PieChart/>component.
Example
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app.js';
require('./style.css');
ReactDOM.render(
<App />,
document.getElementById('root')
);Explanation
Here’s how we can modify charts using the following properties:
animate: This is a boolean that animates elements on the mount.animationDuration: This is the time in milliseconds to which we want the animation to occur.animationEasing: This is the way we want the animation to ease as per the various CSS easing types.center: The x and y coordinates, relative to the center.data: An array of objects containing information about the object. Each object contains a title, color, and value key.lineWidth: This is the line width of each of the pie chart segments.lengthAngle: Total angle taken by the chart that can be negative or positive.paddingAngle: This is the angle between two segments of the pie chart.radius: This is the radius of the chart relative to the view box.rounded: This is a boolean that rounds each cap element segment.startAngle: Start angle of the first segment.viewBoxSize: Width and Height of SVGviewBoxattribute.labelStyle: Each label has a style object applied to it. Returns the style for each label if the function is set.label: A label value or the SVG element to be presented as label is returned by this method.labelPosition: Position of the label with relation to the origin. Percentage of the radius of the chart.
With these properties, we're able to build applications and integrate pie charts into them.