1.0.3 â€Ē Published 5 months ago

@aniruddha1806/pie-chart v1.0.3

Weekly downloads
-
License
MIT
Repository
-
Last release
5 months ago

React Pie Chart

A powerful, customizable pie chart component for React applications with TypeScript support. Perfect for visualizing proportional data with interactive features, animations, and flexible styling options.

Installation

npm install @aniruddha1806/pie-chart

Features

  • ðŸĨ§ Interactive pie charts and donut charts
  • 🎭 Smooth animations with multiple easing options
  • ðŸ–ąïļ Hover effects and click handlers
  • 📊 Interactive tooltips with customizable formatting
  • 🏷ïļ Configurable legend with multiple positioning options
  • ðŸŽĻ Extensive customization (colors, radius, thickness, start angle)
  • ðŸ“ą Responsive SVG-based rendering
  • 🔄 Scroll-triggered animations
  • 📝 TypeScript support with full type definitions
  • â™ŋ Accessibility-friendly structure
  • ðŸŠķ Zero dependencies for chart rendering

Quick Start

Basic Pie Chart

import PieChart from '@aniruddha1806/pie-chart';

function App() {
  const data = [
    { label: 'Desktop', value: 45, color: '#3b82f6' },
    { label: 'Mobile', value: 35, color: '#10b981' },
    { label: 'Tablet', value: 20, color: '#f59e0b' }
  ];

  return (
    <PieChart
      data={data}
      width={400}
      height={400}
      showLegend={true}
      animate={true}
    />
  );
}

Donut Chart

import PieChart from '@aniruddha1806/pie-chart';

function DonutExample() {
  const data = [
    { label: 'Sales', value: 120000 },
    { label: 'Marketing', value: 80000 },
    { label: 'Development', value: 150000 },
    { label: 'Support', value: 60000 }
  ];

  return (
    <PieChart
      data={data}
      width={500}
      height={500}
      donut={true}
      donutThickness={40}
      legendPosition="right"
      animate={true}
      animationDuration={800}
    />
  );
}

Props

Core Props

PropTypeDefaultDescription
dataPieChartData[]requiredChart data array
widthnumber \| string"100%"Chart width
heightnumber \| string"100%"Chart height
radiusnumber50Chart radius (SVG units)

Styling Props

PropTypeDefaultDescription
classNamestringundefinedCSS class for container
sliceClassNamestringundefinedCSS class for slices
tooltipClassNamestringundefinedCSS class for tooltips
legendClassNamestringundefinedCSS class for legend
colorsstring[]default paletteColor palette for slices

Donut Props

PropTypeDefaultDescription
donutbooleanfalseEnable donut chart mode
donutThicknessnumber30Thickness of donut ring

Animation Props

PropTypeDefaultDescription
animatebooleantrueEnable animations
animationDurationnumber500Animation duration (ms)
animationEasing"linear" \| "easeIn" \| "easeOut" \| "easeInOut""easeOut"Animation easing
animateOnScrollbooleantrueTrigger animation on scroll
startAnglenumber0Starting angle (degrees)

Legend Props

PropTypeDefaultDescription
showLegendbooleantrueShow legend
legendPosition"top" \| "right" \| "bottom" \| "left""right"Legend position

Interaction Props

PropTypeDefaultDescription
onSliceClick(data: PieChartData, index: number) => voidundefinedSlice click handler
tooltipFormat(label: string, value: number, percentage: number) => stringundefinedCustom tooltip formatter
percentageFormatter(percentage: number) => stringdefaultPercentage formatter

Data Types

type PieChartData = {
  label: string;
  value: number;
  color?: string;
};

Examples

Sales Dashboard

Complete sales breakdown with interactive features:

import { useState } from 'react';
import PieChart from '@aniruddha1806/pie-chart';

function SalesDashboard() {
  const [selectedSlice, setSelectedSlice] = useState(null);

  const salesData = [
    { label: 'Online Sales', value: 450000, color: '#3b82f6' },
    { label: 'Retail Stores', value: 320000, color: '#10b981' },
    { label: 'Wholesale', value: 180000, color: '#f59e0b' },
    { label: 'Direct Sales', value: 120000, color: '#ef4444' },
    { label: 'Partnerships', value: 80000, color: '#8b5cf6' }
  ];

  const handleSliceClick = (data, index) => {
    setSelectedSlice(data);
    console.log(`Clicked on ${data.label}: $${data.value.toLocaleString()}`);
  };

  const formatTooltip = (label, value, percentage) => {
    return `${label}: $${value.toLocaleString()} (${percentage.toFixed(1)}%)`;
  };

  return (
    <div style={{ padding: '20px' }}>
      <h2>Sales Breakdown by Channel</h2>
      
      <PieChart
        data={salesData}
        width={600}
        height={400}
        onSliceClick={handleSliceClick}
        tooltipFormat={formatTooltip}
        legendPosition="right"
        animate={true}
        animationDuration={1000}
        animationEasing="easeInOut"
      />
      
      {selectedSlice && (
        <div style={{ 
          marginTop: '20px', 
          padding: '16px', 
          backgroundColor: '#f8fafc',
          borderRadius: '8px',
          border: '1px solid #e2e8f0'
        }}>
          <h3>Selected: {selectedSlice.label}</h3>
          <p>Revenue: ${selectedSlice.value.toLocaleString()}</p>
          <p>Percentage: {((selectedSlice.value / salesData.reduce((sum, item) => sum + item.value, 0)) * 100).toFixed(1)}%</p>
        </div>
      )}
    </div>
  );
}

TypeScript Usage

The component provides full TypeScript support:

import PieChart, { PieChartData, PieChartProps } from '@aniruddha1806/pie-chart';
import { useState, useCallback } from 'react';

interface SalesData {
  category: string;
  amount: number;
  color?: string;
}

interface ChartConfig {
  title: string;
  showPercentages: boolean;
  animationSettings: {
    duration: number;
    easing: "linear" | "easeIn" | "easeOut" | "easeInOut";
  };
}

const SalesAnalytics: React.FC = () => {
  const [salesData, setSalesData] = useState<SalesData[]>([
    { category: 'Product A', amount: 150000, color: '#3b82f6' },
    { category: 'Product B', amount: 120000, color: '#10b981' },
    { category: 'Product C', amount: 90000, color: '#f59e0b' }
  ]);

  const transformToChartData = useCallback((data: SalesData[]): PieChartData[] => {
    return data.map(item => ({
      label: item.category,
      value: item.amount,
      color: item.color
    }));
  }, []);

  const handleSliceClick = useCallback((data: PieChartData, index: number): void => {
    console.log(`Clicked on \${data.label}: \${data.value}`);
    // Handle slice click logic
  }, []);

  const formatTooltip = useCallback((
    label: string, 
    value: number, 
    percentage: number
  ): string => {
    return `\${label}: $\${value.toLocaleString()} (\${percentage.toFixed(1)}%)`;
  }, []);

  const chartConfig: ChartConfig = {
    title: 'Sales by Product',
    showPercentages: true,
    animationSettings: {
      duration: 1000,
      easing: 'easeInOut'
    }
  };

  const chartData = transformToChartData(salesData);

  const pieChartProps: PieChartProps = {
    data: chartData,
    width: 500,
    height: 400,
    donut: true,
    donutThickness: 50,
    animate: true,
    animationDuration: chartConfig.animationSettings.duration,
    animationEasing: chartConfig.animationSettings.easing,
    onSliceClick: handleSliceClick,
    tooltipFormat: formatTooltip,
    legendPosition: 'right',
    showLegend: true
  };

  return (
    <div>
      <h2>{chartConfig.title}</h2>
      <PieChart {...pieChartProps} />
      
      <div>
        <h3>Sales Summary:</h3>
        {salesData.map(item => (
          <div key={item.category}>
            <strong>{item.category}:</strong> ${item.amount.toLocaleString()}
          </div>
        ))}
      </div>
    </div>
  );
};
1.0.3

5 months ago

1.0.2

7 months ago

1.0.1

7 months ago

1.0.0

7 months ago