Recharts - Documentation

Getting Started

Installation

Recharts can be easily installed using npm or yarn. For npm, open your terminal and run:

npm install recharts

For yarn, use:

yarn add recharts

After installation, you’ll need to import the necessary components into your project.

Basic Example

This simple example demonstrates a basic line chart using Recharts:

import React from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts';

const data = [
  { name: 'Page A', uv: 4000, pv: 2400, amt: 2400 },
  { name: 'Page B', uv: 3000, pv: 1398, amt: 2210 },
  { name: 'Page C', uv: 2000, pv: 9800, amt: 2290 },
  { name: 'Page D', uv: 2780, pv: 3908, amt: 2000 },
  { name: 'Page E', uv: 1890, pv: 4800, amt: 2181 },
  { name: 'Page F', uv: 2390, pv: 3800, amt: 2500 },
  { name: 'Page G', uv: 3490, pv: 4300, amt: 2100 },
];

const MyLineChart = () => {
  return (
    <LineChart width={500} height={300} data={data}>
      <CartesianGrid strokeDasharray="3 3" />
      <XAxis dataKey="name" />
      <YAxis />
      <Tooltip />
      <Legend />
      <Line type="monotone" dataKey="pv" stroke="#8884d8" />
      <Line type="monotone" dataKey="uv" stroke="#82ca9d" />
    </LineChart>
  );
};

export default MyLineChart;

This code renders a line chart with two lines (“pv” and “uv”), an X-axis showing the page names, a Y-axis, a grid, a tooltip for data display, and a legend. Remember to adjust the width and height properties to fit your layout.

Import Statements

Recharts utilizes a component-based architecture. You import the specific components you need, rather than importing the entire library. Common imports include:

import React from 'react';
import {
  LineChart, Line, BarChart, Bar, PieChart, Pie,
  XAxis, YAxis, CartesianGrid, Tooltip, Legend,
  RadialBar, RadialBarChart,
  // ... other components as needed
} from 'recharts';

This imports components for line charts, bar charts, pie charts, and their respective axes, grids, tooltips, and legends. Consult the Recharts documentation for a complete list of available components.

Understanding Components

Recharts components are structured hierarchically. The top-level component, such as <LineChart>, <BarChart>, or <PieChart>, acts as a container for other components. These “child” components define the chart’s axes, data representation, styling, and interactive elements. For instance:

Each component offers various properties for customization (e.g., styling, data formatting, etc.). Refer to the Recharts documentation for detailed information on each component’s properties and usage.

Core Components

LineChart

The LineChart component renders line charts, ideal for visualizing trends over time or across categories. It requires a data prop, an array of objects, where each object represents a data point. Key properties include:

Child components like <Line>, <XAxis>, <YAxis>, <CartesianGrid>, <Tooltip>, and <Legend> are used to customize the chart’s appearance and interactivity. Each <Line> component needs a dataKey prop specifying which data field to use for the line’s Y-values.

BarChart

The BarChart component renders bar charts, useful for comparing discrete values across categories. Similar to LineChart, it takes a data prop (array of objects) and offers properties for width, height, and margins. Key differences lie in the child components used:

AreaChart

AreaChart is similar to LineChart but fills the area under the line, highlighting the cumulative value. It uses the same data prop and child components as LineChart, but with a <Area> component instead of <Line>. <Area> shares similar properties to <Line>, including dataKey, stroke, and fill.

ScatterChart

ScatterChart creates scatter plots showing the relationship between two variables. It uses a data prop and renders points based on the dataKey values in child <Scatter> components. Each <Scatter> needs dataKey properties for both X and Y coordinates.

PieChart

PieChart displays data as a pie chart, ideal for showing proportions or percentages. It takes a data prop and uses <Pie> components to define each pie slice. The <Pie> component requires a dataKey for the slice’s value and optionally a nameKey for labels.

RadarChart

RadarChart renders radar charts (spider charts), showing multiple variables at different levels. It takes a data prop and utilizes <Radar> and <PolarGrid> components. Data is structured differently than other charts, with each data point representing a value for a specific category along a radius.

Treemap

Treemap displays hierarchical data as nested rectangles, with the size of each rectangle proportional to its value. It requires a data prop in a hierarchical structure, often represented as nested objects or arrays. The layout and appearance are governed by specific properties within the Treemap component itself and its child <Treemap.Rectangle> component.

ComposedChart

ComposedChart allows combining different chart types within a single chart area. This enables showing multiple data series using different chart representations, such as combining line and bar charts. It uses a similar structure to other chart types but can include multiple child components like <Line>, <Bar>, <Area>, etc., to visualize various datasets simultaneously. Proper use of dataKey properties and potentially stackId for stacking is crucial for clear representation.

Cartesian Charts

Axes

Recharts provides XAxis and YAxis components to define the axes of Cartesian charts (LineChart, BarChart, AreaChart, ScatterChart, ComposedChart). Key properties include:

CartesianGrid

CartesianGrid adds a grid to Cartesian charts, improving readability. Key properties:

Tooltip

Tooltip creates interactive tooltips that display detailed data on mouse hover. Key features:

Legend

Legend displays a legend showing the data series and their corresponding colors or symbols. Key properties:

ReferenceLines

ReferenceLine adds horizontal or vertical lines to a chart, highlighting specific data points or thresholds. Key properties:

Brush

Brush adds a brushing and zooming functionality to the chart. The user can select a region of the chart to zoom into, or brush across the data to highlight a specific interval. It requires careful integration with other components, often needing a syncId prop to coordinate zoom/brush between multiple charts.

ResponsiveContainer

ResponsiveContainer makes charts responsive to their parent container’s size. It automatically adjusts the chart dimensions to fit the available space. This is essential for creating charts that work well on different screen sizes. Simply wrap your chart component inside a ResponsiveContainer.

Polar Charts

PolarGrid

PolarGrid is a fundamental component for polar charts (RadarChart, RadialBarChart, RadialBar). It renders the grid lines within the polar coordinate system. Key properties include:

PolarAngleAxis

PolarAngleAxis renders the angle axis of polar charts. This axis is typically used to represent categories or labels around the circumference of the chart. Key properties include:

PolarRadiusAxis

PolarRadiusAxis renders the radius axis of polar charts. This axis typically represents numerical values extending from the center outwards. Key properties include:

PolarNetwork

PolarNetwork is a component that is part of RadarChart for creating network-like connections between data points. Although it’s not always directly used independently like other components, understanding its role within RadarChart is crucial. It’s responsible for connecting the data points on the radar chart with lines or arcs, visually highlighting the relationships between them. Its configuration usually happens implicitly through the Radar component within the RadarChart. Direct customization of PolarNetwork is less common than configuring the styling of the lines within the <Radar> component.

Shapes and Components

Line

The <Line> component renders a line in Cartesian charts (LineChart, ComposedChart). Key properties:

Area

<Area> renders an area chart in (AreaChart, ComposedChart). It’s similar to <Line>, but fills the area under the line. Key properties:

Bar

<Bar> renders bars in (BarChart, ComposedChart). Key properties:

Scatter

<Scatter> renders points in ScatterChart. Key properties:

Pie

<Pie> renders slices in PieChart. Key properties:

Cell

<Cell> is a generic component used for individual data elements within charts. It’s primarily used for styling individual bars, points, or areas. Key properties:

Rectangle

<Rectangle> draws a rectangle on the chart. This provides flexibility to add custom shapes beyond built-in chart elements. Standard properties like x, y, width, height, fill, and stroke are used.

Label

<Label> adds labels to charts, providing additional information. Key properties:

Text

<Text> is a generic text component. Similar to Label but usually added more manually for detailed customization.

Symbol

<Symbol> renders symbols in charts, usually small shapes marking points. Similar to the dot in the <Line> component but with more flexibility. It allows specifying a custom shape using a function that renders a path or SVG element.

Data Handling and Customization

Data Adapters

Recharts doesn’t impose strict data structures. However, its components expect data in specific formats. Data adapters help transform your raw data into a format suitable for Recharts components. While not explicitly provided as separate components, the process involves using JavaScript functions to map and restructure your data. For instance, you might need to:

Customizing Tooltips

Recharts provides extensive tooltip customization through the Tooltip component’s content prop. This prop accepts a function that receives a payload object containing data for the hovered element. You can create custom tooltip components or functions using this payload to render whatever information you need. You might dynamically generate HTML, access specific data fields from the payload, and adjust the tooltip’s layout to create informative and visually pleasing tooltips.

Customizing Legends

Similar to tooltips, legends can be customized. While Recharts provides default legend rendering, you can adjust the legend’s layout (layout, align), add custom icon shapes, and modify how the legend items are formatted using CSS or inline styles applied to the legend wrapper or individual legend items. You might need to inspect the structure of the payload passed to the legend rendering function for precise control.

Data Formatting

Data formatting is crucial for clear data presentation. Recharts offers several ways:

Handling Events

Recharts components emit various events (e.g., onClick, onMouseOver, onMouseOut). You can attach event handlers to these events to implement interactive features. Common use cases include:

Animations

Recharts supports animations to improve the user experience. Animations are enabled by default for many chart types, creating smooth transitions as data changes. You can control animation properties such as duration, easing functions, and whether or not animations are used via props like animationDuration available in many components. Turning off animations can be beneficial for performance with very large datasets.

Advanced Concepts

Composing Charts

Recharts excels at composing multiple charts. The ComposedChart component allows combining different chart types (e.g., line and bar charts) within a single chart area. This requires careful consideration of data structures, ensuring consistent X-axis scales and appropriate use of dataKey properties to correctly map data series to the respective chart types. You’ll often leverage stacking (stackId prop) for visual clarity when combining multiple bar or area charts. Proper use of legends and tooltips is critical for easily interpreting the combined data.

Dynamic Updates

Updating charts dynamically is crucial for interactive applications. Recharts efficiently handles data updates through React’s state management. Changes to your component’s state, which influences the chart’s data prop, will trigger a re-render and update the chart’s visualization. This process is inherently optimized by React’s virtual DOM, making updates efficient even with frequent changes. However, for extremely high-frequency updates, consider implementing techniques to reduce unnecessary re-renders, potentially using useMemo or useCallback hooks.

Custom Components

Extend Recharts by creating custom components. This allows tailoring charts to specific needs. You can extend existing components or create entirely new ones, leveraging Recharts’ underlying SVG rendering capabilities. Consider creating custom shapes, axes, or tooltips. For example, you might build a custom component that overlays a specific shape based on particular data conditions or adds annotation. Remember to adhere to Recharts’ component structure and prop conventions for seamless integration.

Integrating with React

Recharts is a React component library, seamlessly integrating with React’s lifecycle methods and state management systems. Use React’s state and hooks to manage chart data and trigger updates, leverage React’s component structure for organization, and employ React’s event handling mechanism for interactive features. Familiarize yourself with React’s best practices, such as using functional components and hooks, for optimal performance and code maintainability.

Performance Optimization

Performance is key, particularly with large datasets. Optimize Recharts charts by:

Accessibility

Ensure Recharts charts are accessible. This involves:

Troubleshooting

Common Issues

Several common issues arise when working with Recharts:

Debugging Tips

Effective debugging is crucial:

Error Handling

Recharts doesn’t have built-in comprehensive error handling for invalid data or incorrect configurations. The responsibility for handling errors lies primarily with the developer. Best practices include:

API Reference

Component Props

This section provides a comprehensive list of props for each Recharts component. Due to the extensive number of components and their properties, a complete listing here is impractical. However, the following outlines the general approach to understanding component props:

Each component’s documentation (typically found on the official Recharts website or through JSDoc comments in the source code) details its specific props. Props are generally categorized as follows:

To find detailed information about the props for a specific component (e.g., <LineChart>), consult the Recharts documentation. Look for the component’s API reference, which will list all available props with descriptions and data types.

Utility Functions

Recharts provides several utility functions to assist in chart creation and data manipulation. These are not typically directly used as React components, but are helper functions which are called within your application code. Again, a complete list is impractical here; the details of available utility functions are best found in the Recharts documentation. However, you can generally expect functions related to:

The documentation will provide examples and descriptions of how to utilize these utility functions effectively. Remember to check the official documentation for the most up-to-date information on available utility functions and their usage.