recharts
Build composable, responsive React charts with Recharts library. Use when creating data visualizations including line charts, area charts, bar charts, pie charts, scatter plots, and composed charts. Handles chart customization, responsive sizing, tooltips, legends, axes configuration, performance optimization, and accessibility.
What this skill does
# Recharts
React charting library built on top of D3 for composable, declarative data visualization.
## Quick Start
### 1. Install Recharts
```bash
npm install recharts
```
### 2. Basic Chart Structure
All Recharts charts follow the same pattern:
```jsx
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
const data = [
{ name: 'Jan', sales: 4000, profit: 2400 },
{ name: 'Feb', sales: 3000, profit: 1398 },
{ name: 'Mar', sales: 2000, profit: 9800 },
];
<ResponsiveContainer width="100%" height={300}>
<LineChart data={data}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="sales" stroke="#8884d8" />
<Line type="monotone" dataKey="profit" stroke="#82ca9d" />
</LineChart>
</ResponsiveContainer>
```
## Core Concepts
### Data Format
Recharts expects data as an **array of objects**. Each object represents a data point:
```javascript
const data = [
{ month: 'Jan', revenue: 4000, expenses: 2400 },
{ month: 'Feb', revenue: 3000, expenses: 1398 },
];
```
Use `dataKey` props to map object properties to chart components:
- `dataKey="revenue"` - maps to the revenue property
- `dataKey={(entry) => entry.revenue - entry.expenses}` - function for computed values
### Component Composition
Charts are built by nesting specialized components:
**Sizing**: Use the `responsive` prop (v3.3+), `ResponsiveContainer` wrapper, or set `width`/`height` directly
**Chart types** (choose one):
- `LineChart` - Line and area visualizations
- `BarChart` - Bar and column charts
- `AreaChart` - Stacked and filled area charts
- `PieChart` - Pie and donut charts
- `ScatterChart` - Scatter plots and bubble charts
- `ComposedChart` - Mixed chart types
- `RadarChart` - Radar/spider charts
- `RadialBarChart` - Circular bar charts
**Common child components**:
- `XAxis` / `YAxis` - Axis configuration
- `CartesianGrid` - Grid lines
- `Tooltip` - Hover information
- `Legend` - Series identification
- `Line` / `Bar` / `Area` / `Pie` - Data series visualization
## Chart Patterns by Type
### Line Charts
```jsx
<LineChart data={data}>
<XAxis dataKey="name" />
<YAxis />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="value" stroke="#8884d8" strokeWidth={2} dot={{ r: 4 }} />
</LineChart>
```
**Key props**:
- `type`: "monotone" (smooth), "linear", "step", "natural"
- `stroke`: line color
- `strokeWidth`: line thickness
- `dot`: point styling (set to `false` to hide)
- `activeDot`: hovered point styling
- `connectNulls`: true to connect gaps
### Area Charts
```jsx
<AreaChart data={data}>
<defs>
<linearGradient id="colorValue" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#8884d8" stopOpacity={0.8}/>
<stop offset="95%" stopColor="#8884d8" stopOpacity={0}/>
</linearGradient>
</defs>
<XAxis dataKey="name" />
<YAxis />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip />
<Area type="monotone" dataKey="value" stroke="#8884d8" fillOpacity={1} fill="url(#colorValue)" />
</AreaChart>
```
**Stacked areas**:
```jsx
<Area type="monotone" dataKey="sales" stackId="1" stroke="#8884d8" fill="#8884d8" />
<Area type="monotone" dataKey="profit" stackId="1" stroke="#82ca9d" fill="#82ca9d" />
```
### Bar Charts
```jsx
<BarChart data={data}>
<XAxis dataKey="name" />
<YAxis />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip />
<Legend />
<Bar dataKey="sales" fill="#8884d8" radius={[4, 4, 0, 0]} />
<Bar dataKey="profit" fill="#82ca9d" radius={[4, 4, 0, 0]} />
</BarChart>
```
**Key props**:
- `fill`: bar color
- `radius`: rounded corners [topLeft, topRight, bottomRight, bottomLeft] or single number for all corners
- `barSize`: fixed bar width
- `stackId`: group bars into stacks
- `shape`: custom bar shape (function or element)
**Stacked bars**:
```jsx
<Bar dataKey="sales" stackId="a" fill="#8884d8" />
<Bar dataKey="profit" stackId="a" fill="#82ca9d" />
```
**Rounded stacked bars** (use `BarStack` to round the whole stack):
```jsx
import { BarStack } from 'recharts';
<BarChart data={data}>
<BarStack stackId="a" radius={[4, 4, 0, 0]}>
<Bar dataKey="sales" fill="#8884d8" />
<Bar dataKey="profit" fill="#82ca9d" />
</BarStack>
</BarChart>
```
### Pie Charts
```jsx
const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];
<PieChart>
<Pie
data={data}
dataKey="value"
nameKey="name"
cx="50%"
cy="50%"
innerRadius={60}
outerRadius={80}
paddingAngle={5}
shape={(props) => <Sector {...props} fill={COLORS[props.index % COLORS.length]} />}
/>
<Tooltip />
<Legend />
</PieChart>
```
**Key props**:
- `innerRadius`: creates donut chart when > 0
- `outerRadius`: pie size
- `paddingAngle`: gap between slices
- `startAngle` / `endAngle`: partial pie (default: 0 to 360)
- `label`: shows values on slices
- `shape`: custom render for each slice (replaces deprecated `Cell` component)
### Scatter Charts
```jsx
<ScatterChart>
<XAxis type="number" dataKey="x" name="X Axis" />
<YAxis type="number" dataKey="y" name="Y Axis" />
<CartesianGrid />
<Tooltip cursor={{ strokeDasharray: '3 3' }} />
<Scatter name="Series A" data={data} fill="#8884d8" />
</ScatterChart>
```
### Composed Charts
Mix multiple chart types:
```jsx
<ComposedChart data={data}>
<XAxis dataKey="name" />
<YAxis />
<CartesianGrid stroke="#f5f5f5" />
<Tooltip />
<Legend />
<Area type="monotone" dataKey="total" fill="#8884d8" stroke="#8884d8" />
<Bar dataKey="sales" barSize={20} fill="#413ea0" />
<Line type="monotone" dataKey="profit" stroke="#ff7300" />
</ComposedChart>
```
## Responsive Sizing
### Option 1: `responsive` prop (Recharts 3.3+, recommended)
Set `responsive` on the chart itself. Uses standard CSS sizing rules:
```jsx
<LineChart data={data} width="100%" height={300} responsive>
{/* chart components */}
</LineChart>
```
Works with flexbox and CSS grid layouts. Also supports CSS `style` props:
```jsx
<LineChart data={data} responsive style={{ maxWidth: 800, width: '100%', aspectRatio: '16/9' }}>
{/* chart components */}
</LineChart>
```
### Option 2: `ResponsiveContainer` (older versions)
For Recharts < 3.3, wrap chart in `ResponsiveContainer`:
```jsx
<ResponsiveContainer width="100%" height={300}>
<LineChart data={data}>
{/* chart components */}
</LineChart>
</ResponsiveContainer>
```
**Critical**: `ResponsiveContainer` must have a parent with defined dimensions. Height must be a number, not a percentage.
### Static sizing
Set `width` and `height` directly as pixels or percentages:
```jsx
<LineChart data={data} width={600} height={300}>
{/* chart components */}
</LineChart>
```
## Axes Configuration
### XAxis / YAxis Props
```jsx
<XAxis
dataKey="name" // property to display
type="category" // "category" or "number"
domain={[0, 'dataMax']} // axis range
tick={{ fill: '#666' }} // tick styling
tickFormatter={(value) => `$${value}`} // format labels
angle={-45} // rotate labels
textAnchor="end" // text alignment
height={60} // extra space for labels
/>
```
### Axis Types
- **Category axis** (default for X): Treats values as discrete labels
- **Number axis** (default for Y): Treats values as continuous scale
### Custom Domains
Control axis range:
```jsx
// Fixed range
<YAxis domain={[0, 100]} />
// Auto with padding
<YAxis domain={[0, 'auto']} />
// Data-based with overflow allowed
<YAxis domain={[0, 'dataMax + 100']} allowDataOverflow />
// Logarithmic scale
<YAxis type="number" scale="log" domain={['auto', 'auto']} />
```
## Customization
### Custom Tooltip
```jsx
const CustomTooltip = ({ active, payload, label }) => {
if (active && payload && payload.length) {
return (
<div className="custom-tooltip">
<p className="label">{`${label}`Related in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.