npm package: @kubit-ui-web/react-charts
Description: Modern React chart library with TypeScript support - Create beautiful, interactive, and accessible data visualizations with ease. Features bar charts, line charts, pie charts, and more!
Author: Kubit Team
Latest version: 1.11.6

# Kubit React Charts

<p align="center">
  <a href="https://kubit-ui.com">
    <picture>
      <source media="(prefers-color-scheme: dark)" srcset="https://github.com/kubit-ui/kubit-react-charts/raw/cms/assets/readme_logo.png">
      <img src="hhttps://github.com/kubit-ui/kubit-react-charts/raw/cms/assets/readme_logo.png" width="70%">
    </picture>
  </a>
</p>

<p align="center">
  <strong>A modern React charting library</strong><br/>
  Reusable, accessible, and interactive SVG components for data visualization
</p>

<p align="center">
  <img src="https://img.shields.io/npm/v/@kubit-ui-web/react-charts" alt="Version" />
  <img src="https://img.shields.io/badge/React-18.3.1-blue?logo=react" alt="React version" />
  <img src="https://img.shields.io/badge/TypeScript-5.9.2-blue?logo=typescript" alt="TypeScript version" />
  <img src="https://img.shields.io/badge/license-Apache%202.0-blue" alt="License" />
</p>

---

## Table of Contents

### For Library Users

- [Features](#features)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Available Components](#available-components)
- [API Reference](#api-reference)

### For Contributors & Developers

- [Development Setup](#development-setup)
- [Project Architecture](#project-architecture)
- [Development Scripts](#development-scripts)
- [Contributing Guidelines](#contributing-guidelines)
- [License](#license)

---

# For Library Users

> 💡 **Cross-platform**: Kubit Charts is also available for [Android](https://github.com/kubit-ui/kubit-android-charts) and [iOS](https://github.com/kubit-ui/kubit-ios-charts) platforms, enabling consistent chart experiences across all your applications.

## Features

**Composable**: Modular architecture where each chart is composed of specialized elements  
**Performant**: Optimized SVG rendering with React 18  
**Accessible**: WCAG compliant with keyboard navigation support  
**Customizable**: Flexible styling and granular configurations  
**Responsive**: Adaptable to different screen sizes  
**TypeScript**: Fully typed for better developer experience  
**SSR Ready**: Complete Server-Side Rendering support for Next.js, Remix, Gatsby, and more  
**Error Handling**: Advanced centralized error management system with detailed debugging  
**Production Safe**: Built-in logging system that's automatically optimized for production builds  
**Tested**: Complete coverage with Vitest and Testing Library

## Installation

### Yarn (Recommended)

```bash
yarn add @kubit-ui-web/react-charts
```

### NPM

```bash
npm install @kubit-ui-web/react-charts
```

### Peer Dependencies

This library requires React as a peer dependency:

```bash
npm install react react-dom
# or
yarn add react react-dom
```

**Compatible versions:**

- React: ^18.3.1
- React DOM: ^18.3.1

### Tree-Shaking Support

The library supports granular imports for optimal bundle size:

```typescript
// Import specific charts only
import { BarChart } from '@kubit-ui-web/react-charts/charts/barChart';
import { LineChart } from '@kubit-ui-web/react-charts/charts/lineChart';
// Import specific components only
import { Node } from '@kubit-ui-web/react-charts/components/node';
import { Path } from '@kubit-ui-web/react-charts/components/path';
// Import specific utilities only
import { logger } from '@kubit-ui-web/react-charts/utils/logger';
import { isBrowser } from '@kubit-ui-web/react-charts/utils/ssr';
```

## Quick Start

### Importing Components

```typescript
// Import complete charts
import { BarChart, LineChart, PieChart } from '@kubit-ui-web/react-charts';
// Import specific components
import { Node, Path, Plot } from '@kubit-ui-web/react-charts/components';
// Import types
import type { BarOrientation, ChartData } from '@kubit-ui-web/react-charts/types';
// Import utilities
import { configureLogger, logger } from '@kubit-ui-web/react-charts/utils';
import { createSVGElement, isBrowser, safeWindow } from '@kubit-ui-web/react-charts/utils';
```

### LineChart Example

```tsx
import { LineChart } from '@kubit-ui-web/react-charts';
import React from 'react';

const data = [
  { year: '2020', sales: 100, profit: 20 },
  { year: '2021', sales: 150, profit: 35 },
  { year: '2022', sales: 180, profit: 45 },
  { year: '2023', sales: 200, profit: 60 },
];

function MyLineChart() {
  return (
    <LineChart data={data} xKey="year" width="100%" height="400px">
      <LineChart.Path dataKey="sales" stroke="#0078D4" strokeWidth={2} />
      <LineChart.Path dataKey="profit" stroke="#FF6B35" strokeWidth={2} />
      <LineChart.XAxis position="BOTTOM" showTickLines />
      <LineChart.YAxis position="LEFT" valueFormatter={val => `$${val}k`} />
    </LineChart>
  );
}
```

### BarChart Example

```tsx
import { BarChart, BarOrientation } from '@kubit-ui-web/react-charts';
import React from 'react';

const data = [
  { category: 'A', value: 30 },
  { category: 'B', value: 45 },
  { category: 'C', value: 25 },
  { category: 'D', value: 60 },
];

function MyBarChart() {
  return (
    <BarChart
      data={data}
      pKey="category"
      orientation={BarOrientation.VERTICAL}
      gapBetweenBars={5}
      width="100%"
      height="400px"
    >
      <BarChart.Path
        dataKey="value"
        dataIdx={0}
        barConfig={{
          barWidth: 40,
          singleConfig: [{ color: '#0078D4', coverage: 100 }],
        }}
      />
      <BarChart.XAxis position="BOTTOM" />
      <BarChart.YAxis position="LEFT" />
    </BarChart>
  );
}
```

### Error Handling Example

```tsx
import { LineChart } from '@kubit-ui-web/react-charts';
import type { ChartErrorCollection } from '@kubit-ui-web/react-charts/types';
import React from 'react';

function ChartWithErrorHandling() {
  const handleErrors = (errors: ChartErrorCollection) => {
    // Centralized error handling
    console.warn('Chart errors:', errors);
    // Display user-friendly messages or retry logic
  };

  return (
    <LineChart data={data} xKey="year" onErrors={handleErrors} width="100%" height="400px">
      <LineChart.Path dataKey="sales" stroke="#0078D4" />
      <LineChart.XAxis position="BOTTOM" />
      <LineChart.YAxis position="LEFT" />
    </LineChart>
  );
}
```

### SSR (Server-Side Rendering) Support

```tsx
import { LineChart, isBrowser, safeWindow } from '@kubit-ui-web/react-charts';
import React from 'react';

function SSRCompatibleChart() {
  // Safe browser API access
  const windowWidth = isBrowser() ? safeWindow()?.innerWidth || 800 : 800;

  return (
    <LineChart data={data} xKey="year" width={windowWidth} height="400px">
      <LineChart.Path dataKey="sales" stroke="#0078D4" />
    </LineChart>
  );
}
```

### Logger Configuration

```tsx
import { configureLogger, logger } from '@kubit-ui-web/react-charts';

// Configure logger for development
configureLogger({
  enabled: true,
  minLevel: 'debug',
  prefix: '[MyApp Charts]',
});

// Use logger in your components
function MyComponent() {
  logger.info('Chart rendering started');
  // Chart implementation
}
```

## Available Components

### Main Charts

| Component       | Description                   | Use Cases                           |
| --------------- | ----------------------------- | ----------------------------------- |
| **`LineChart`** | Multi-series line chart       | Time trends, metric comparisons     |
| **`BarChart`**  | Horizontal/vertical bar chart | Category comparisons, discrete data |
| **`PieChart`**  | Circular chart with segments  | Part-to-whole relationships         |

### Base Components

| Component       | Description                   |
| --------------- | ----------------------------- |
| **`Plot`**      | Base SVG container for charts |
| **`Path`**      | Customizable SVG path element |
| **`Node`**      | Interactive points in charts  |
| **`Line`**      | Lines and connectors          |
| **`Bar`**       | Rectangular bars              |
| **`ChartText`** | Formatted text for labels     |

### Available Hooks

| Hook           | Description                              |
| -------------- | ---------------------------------------- |
| **`useFocus`** | Focus state management for accessibility |
| **`useHover`** | Hover detection with callbacks           |

### Utility Functions

| Utility                      | Description                                        |
| ---------------------------- | -------------------------------------------------- |
| **`logger`**                 | Production-safe logging with configurable levels   |
| **`configureLogger`**        | Logger configuration for development/debugging     |
| **`isBrowser`**              | Environment detection for browser vs SSR           |
| **`isServer`**               | Check if running in server-side environment        |
| **`safeWindow`**             | Safe access to window object in SSR environments   |
| **`safeDocument`**           | Safe access to document object in SSR environments |
| **`createSVGElement`**       | SSR-compatible SVG element creation                |
| **`createErrorAccumulator`** | Advanced error management for chart components     |

## API Reference

For detailed API documentation, component props, and advanced examples, please refer to our individual component READMEs:

- [BarChart Documentation](./app/src/charts/barChart/README.md)
- [LineChart Documentation](./app/src/charts/lineChart/README.md)
- [PieChart Documentation](./app/src/charts/pieChart/README.md)

---

# For Contributors & Developers

<p align="center">
  <img src="./app/assets/KubitoJumping.gif" alt="Kubito jumping" width="100" />
</p>

## Development Setup

### Environment Requirements

- Node.js >= 16
- Yarn (recommended) or npm
- Git

### Getting Started

1. **Clone the repository**

   ```bash
   git clone https://github.com/kubit-ui/kubit-react-charts
   cd web-ui-charts/app
   ```

2. **Install dependencies**

   ```bash
   yarn install
   ```

3. **Start development server**
   ```bash
   yarn start
   ```

This will launch Storybook at `http://localhost:6006` where you can interact with all components.

## Project Architecture

```
src/
├── charts/           # High-level chart components
│   ├── barChart/     # BarChart and subcomponents
│   ├── lineChart/    # LineChart and subcomponents
│   └── pieChart/     # PieChart and subcomponents
├── components/       # Reusable SVG base components
│   ├── plot/         # Main SVG container
│   ├── path/         # Path elements
│   ├── node/         # Interactive points
│   ├── line/         # Lines and connectors
│   └── ...
├── hooks/            # Custom hooks
├── types/            # TypeScript definitions
├── utils/            # Shared utility functions
└── storybook/        # Storybook configuration and constants
```

### Composition Pattern

Each chart follows a consistent compositional pattern:

```typescript
const LineChart = Object.assign(LineChartStructure, {
  Path: LineChartPath,
  XAxis: LineChartXAxis,
  YAxis: LineChartYAxis,
  Separator: LineChartSeparator,
});
```

This pattern enables:

- **Flexibility**: Use only the components you need
- **Reusability**: Shared components between different charts
- **Extensibility**: Easy addition of new subcomponents

## Development Scripts

### Main Commands

```bash
# Start Storybook in development mode
yarn start

# Build library for production
yarn dist

# Run tests with coverage
yarn test

# Lint code with ESLint
yarn eslint

# Format code
yarn format

# Build Storybook for production
yarn build

# Changeset commands (for maintainers)
yarn changeset              # Create a changeset manually
yarn changeset:version      # Version packages
yarn changeset:publish      # Publish to NPM
yarn changeset:status       # Check changeset status

# Run accessibility tests
yarn storybook:axe
```

### Build Commands

```bash
# Complete build (ESM + CJS)
yarn dist

# Build in watch mode
yarn dist:watch

# CommonJS only
yarn dist:cjs

# ES Modules only
yarn dist:esm
```

### Testing Commands

```bash
# Unit tests with UI
yarn vitest-report

# Storybook tests
yarn test-storybook

# ESLint only
yarn eslint --fix
```

## Contributing

### Code Standards

- **TypeScript**: Fully typed code
- **ESLint**: Strict configuration with Kubit rules
- **Prettier**: Automatic code formatting
- **Testing**: Minimum 80% coverage

### Contribution Workflow

See our [CONTRIBUTING](./CONTRIBUTING.md) for coding conventions, commit message guidelines, and pull request processes.

### Component Development Guidelines

Please refer to our [development instructions](./.github/copilot-instructions.md) for detailed guidelines on:

- Component structure and patterns
- Naming conventions
- TypeScript usage
- Error handling
- CSS and styling
- Accessibility requirements

## License

This project is licensed under the Apache License 2.0 - see the [LICENSE](./LICENSE) file for details.

---

<p align="center">
  Made with ❤️ by the <strong>Kubit</strong> team <img src="https://github.com/kubit-ui/kubit-react-charts/raw/cms/assets/kubito.png" alt="Kubito" width="15" height="15" />
</p>