skills /"creating-react-recharts-visualizations"
Data Viz Referenced

"creating-react-recharts-visualizations"

"Creates interactive data visualizations using Recharts library in React/TypeScript. Use for building line charts, bar charts, and time series with custom styling and interactivity."

Creating React Recharts Visualizations

Overview

Creates production-ready React components using the Recharts library for data visualization. Specializes in time series line charts and state-level bar charts with TypeScript support, custom tooltips, error bars, and interactive features.

When to Use

  • Building interactive data visualizations in React applications
  • Creating time series charts with confidence intervals
  • Displaying state-level or categorical bar charts
  • Requiring TypeScript-safe chart components
  • Need customizable tooltips, formatting, and styling

Prerequisites

Required packages:

hljs bash
npm install recharts lucide-react

If using shadcn/ui components:

hljs bash
npx shadcn-ui@latest add button input

TypeScript: All components use TypeScript with strict typing.

Bundled Resources

References (references/)

Load these when implementing specific chart types or needing detailed guidance:

  • data-structures.md - Complete TypeScript interfaces for all data shapes
  • time-series-patterns.md - Line chart implementation patterns and examples
  • bar-chart-patterns.md - Bar chart patterns with sorting/filtering
  • three-way-interaction-patterns.md - Faceted dot whisker plots for complex interactions with confidence intervals
  • confidence-intervals-facets.md - Faceted time series with discrete error bars and continuous confidence bands
  • statistical-charts-guide.md - Forest plots and main effects visualizations for regression results and meta-analysis
  • styling-guide.md - Visual design standards and color schemes
  • formatting-rules.md - Number/date formatting rules and helpers
  • testing-guide.md - Validation checklist and edge cases

Assets (assets/)

Production-ready components organized by complexity:

Basic Charts (assets/basic/):

  • time-series-template.tsx - Line chart with error bars and confidence intervals
  • time-series-example.ts - Sample time series data
  • TimeSeriesChart.tsx - Enhanced time series with multiple features
  • bar-chart-template.tsx - Horizontal bar chart with interactivity
  • bar-chart-example.ts - Sample bar chart data
  • StateBarChart.tsx - State-level comparison bar charts

Statistical Visualizations (assets/statistical/):

  • forest-plot.tsx - Forest plots for odds ratios, meta-analysis, regression coefficients
  • main-effects-plot.tsx - Main effects visualization with confidence intervals

Advanced Charts (assets/advanced/):

  • three-way-interaction-template.tsx - Faceted dot whisker plot for 3-way interactions
  • three-way-interaction-example.ts - Sample interaction data
  • faceted-discrete-ci-template.tsx - Faceted time series with discrete confidence intervals (error bars)
  • faceted-continuous-bands-template.tsx - Faceted time series with continuous confidence bands (shaded areas)
  • DualAxisChart.tsx - Dual Y-axis time series with recession periods and time range controls

Specialized Charts (assets/specialized/):

  • AbortionOpinionChart.tsx - Survey opinion visualization with demographic filtering

Core Workflow

Step 1: Identify Chart Type

Line Chart with Time Series:

  • Yearly/temporal data
  • Trend visualization
  • Confidence intervals or error bars
  • See references/time-series-patterns.md

Horizontal Bar Chart:

  • State-level comparisons
  • Categorical rankings
  • Interactive sorting/filtering
  • See references/bar-chart-patterns.md

Faceted Time Series with Confidence Intervals:

  • Comparing multiple groups/demographics side-by-side
  • Survey data across categories (age groups, regions, etc.)
  • Discrete confidence intervals (error bars) for periodic measurements
  • Continuous confidence bands (shaded areas) for trend visualization
  • See references/confidence-intervals-facets.md

Statistical Charts:

  • Forest plots for meta-analysis and regression coefficients
  • Main effects plots with confidence intervals
  • Odds ratio visualizations
  • See assets/statistical/

Advanced Charts:

  • Three-way interaction plots (faceted dot whisker)
  • Dual Y-axis time series with annotations
  • Recession period overlays and time range controls
  • See assets/advanced/

Specialized Visualizations:

  • Domain-specific survey charts
  • Custom filtering and demographic breakdowns
  • See assets/specialized/

Step 2: Structure Data

Data MUST match the TypeScript interfaces defined in references/data-structures.md.

Critical: Validate data structure before rendering to prevent runtime errors.

Step 3: Generate Component

Use templates from assets/ directory organized by type:

Basic:

  • assets/basic/time-series-template.tsx - Line charts with error bars
  • assets/basic/bar-chart-template.tsx - Horizontal bar charts
  • assets/basic/StateBarChart.tsx - State-level comparisons

Statistical:

  • assets/statistical/forest-plot.tsx - Forest plots for odds ratios
  • assets/statistical/main-effects-plot.tsx - Main effects with CIs

Advanced:

  • assets/advanced/three-way-interaction-template.tsx - 3-way interactions
  • assets/advanced/DualAxisChart.tsx - Dual Y-axis time series

Specialized:

  • assets/specialized/AbortionOpinionChart.tsx - Survey visualizations

Step 4: Customize Styling

Apply consistent styling patterns:

  • Colors: Use neutral palette (black/gray) for professional appearance
  • Fonts: System font stack with size hierarchy
  • Spacing: Consistent margins using Recharts margin props
  • See references/styling-guide.md

Step 5: Add Interactivity

Implement standard interactive features:

  • Custom tooltips with formatted values
  • Hover states
  • Sorting controls (bar charts)
  • Search/filter (bar charts)
  • Expand/collapse (bar charts)

Quick Reference

Essential Props Pattern

hljs typescript
// Line Chart <LineChart data={numericData} margin={{ top: 20, right: 30, left: 20, bottom: 20 }}> // Bar Chart <BarChart data={sortedData} layout="vertical" margin={{ right: 20, top: 20, bottom: 40 }}>

Common Axis Configurations

Numeric X-Axis (years):

hljs typescript
<XAxis dataKey="year" type="number" domain={[minYear, maxYear]} tickCount={(maxYear - minYear) / 2} />

Percentage Y-Axis:

hljs typescript
<YAxis tickFormatter={(value) => `${value}%`} />

Value Formatting Pattern

ALWAYS format large numbers with abbreviations:

hljs typescript
if (num >= 1_000_000_000) { formattedValue = (num / 1_000_000_000).toFixed(1) + 'B'; } else if (num >= 1_000_000) { formattedValue = (num / 1_000_000).toFixed(1) + 'M'; } else if (num >= 1_000) { formattedValue = (num / 1_000).toFixed(1) + 'k'; }

Faceted Charts Pattern

Render multiple charts side-by-side for group comparisons:

hljs typescript
const ChartPanel = ({ data, title }) => ( <div style={{ flex: 1, minWidth: '400px' }}> <h3>{title}</h3> <ResponsiveContainer width="100%" height={450}> <LineChart data={data}>{/* Chart components */}</LineChart> </ResponsiveContainer> </div> ); // Render facets <div style={{ display: 'flex', gap: '24px', flexWrap: 'wrap' }}> {Object.entries(facetedData).map(([facetName, facetData]) => ( <ChartPanel key={facetName} data={facetData} title={facetName} /> ))} </div>

Continuous Confidence Bands Pattern

Use stacked areas in ComposedChart for shaded confidence bands:

hljs typescript
// Transform data to create stackable ranges const transformData = (data) => data.map(d => ({ ...d, value_band_lower: d.value - (1.96 * d.standard_error), value_band_range: 2 * 1.96 * d.standard_error })); // In ComposedChart (NOT LineChart) <ComposedChart data={transformData(data)}> <Area dataKey="value_band_lower" stackId="band" fill="transparent" /> <Area dataKey="value_band_range" stackId="band" fill="url(#bandGradient)" /> <Line dataKey="value" stroke="#2563eb" dot={false} /> </ComposedChart>

Critical Requirements

Data Validation

ALWAYS validate for duplicate keys:

hljs typescript
const uniqueYears = new Set(dataYears); if (dataYears.length !== uniqueYears.size) { return <div>Error: Duplicate years detected</div>; }

Error Bars

When displaying confidence intervals, use standard_error with 95% CI:

hljs typescript
<ErrorBar dataKey={(d) => d.standard_error ? (1.96 * d.standard_error) : 0} stroke="#000000" strokeWidth={1} />

Responsive Design

ALWAYS wrap charts in ResponsiveContainer:

hljs typescript
<ResponsiveContainer width="100%" height="100%"> <LineChart>...</LineChart> </ResponsiveContainer>

Animation

Disable animations for data-heavy charts:

hljs typescript
<Line isAnimationActive={false} />

Component Organization

hljs typescript
// Standard component structure export default function ChartName({ data, metadata }: Props) { // 1. State declarations // 2. Data transformations // 3. Validation // 4. Helper functions (tooltips, formatters) // 5. Return JSX }

Common Patterns

Metadata-Driven Formatting

Extract formatting rules from metadata:

hljs typescript
const valueMetadata = dataPointMetadata.find(d => d.id === 'value'); const prefix = valueMetadata?.value_prefix || ''; const suffix = valueMetadata?.value_suffix || '';

Conditional Rendering

Handle missing/null data gracefully:

hljs typescript
.filter((entry): entry is [string, StateData & { overall: number }] => entry[1].overall !== null )

Custom Tooltips

Create informative, styled tooltips:

hljs typescript
const CustomTooltip = ({ active, payload, label }: any) => { if (!active || !payload?.length) return null; return ( <div className="bg-white p-3 border border-gray-200 shadow-lg rounded-lg"> {/* Tooltip content */} </div> ); };

See Also

Implementation Guides (load as needed):

  • references/time-series-patterns.md - Complete time series implementation
  • references/bar-chart-patterns.md - Bar chart with sorting/filtering
  • references/data-structures.md - TypeScript interface definitions
  • references/styling-guide.md - Consistent visual styling
  • references/formatting-rules.md - Value formatting standards
  • references/testing-guide.md - Validation and testing checklist

Copy-Paste Ready Templates:

  • assets/time-series-template.tsx - Production line chart component
  • assets/bar-chart-template.tsx - Production bar chart component
  • assets/time-series-example.ts - Sample time series data
  • assets/bar-chart-example.ts - Sample bar chart data

Troubleshooting

Chart not rendering?

  • Verify data structure matches TypeScript interfaces
  • Check for null/undefined values in required fields
  • Ensure ResponsiveContainer has explicit height

Duplicate key errors?

  • Validate unique keys before rendering
  • Check for duplicate years/categories in data

Formatting issues?

  • Confirm metadata structure matches expected format
  • Verify prefix/suffix are strings (not objects)
  • Test with edge cases (very large/small numbers)

Related Categories