Recharts is a popular, composable charting library built on top of React and D3. It provides a declarative API for creating responsive, interactive charts with extensive customization options. This guide walks through advanced usage of Recharts, including complex chart configurations, custom components, and dashboard implementations.
Prerequisites
Before you begin, make sure you have:
- Node.js version 14.0 or higher installed
- npm, yarn, or pnpm package manager
- A React project (version 16.8 or higher) or create-react-app setup
- Basic knowledge of React hooks (useState, useEffect)
- Familiarity with JavaScript/TypeScript
- Understanding of data visualization concepts
Installation
Install Recharts using your preferred package manager:
npm install recharts
Or with yarn:
yarn add recharts
Or with pnpm:
pnpm add recharts
After installation, your package.json should include:
{
"dependencies": {
"recharts": "^2.0.0",
"react": "^18.0.0",
"react-dom": "^18.0.0"
}
}
Project Setup
Recharts requires minimal setup. Import the components and you're ready to use them.
First Example / Basic Usage
Let's create a simple line chart. Create a new file src/ChartExample.jsx:
// src/ChartExample.jsx
import React from 'react';
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ResponsiveContainer
} from 'recharts';
function ChartExample() {
const data = [
{ name: 'Jan', sales: 35 },
{ name: 'Feb', sales: 28 },
{ name: 'Mar', sales: 34 },
{ name: 'Apr', sales: 32 },
{ name: 'May', sales: 40 },
{ name: 'Jun', sales: 32 }
];
return (
<div style={{ padding: '20px', maxWidth: '800px', margin: '0 auto' }}>
<h2>Basic Recharts Example</h2>
<ResponsiveContainer width="100%" height={400}>
<LineChart data={data}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="sales" stroke="#8884d8" />
</LineChart>
</ResponsiveContainer>
</div>
);
}
export default ChartExample;
Update your App.jsx:
// src/App.jsx
import React from 'react';
import ChartExample from './ChartExample';
import './App.css';
function App() {
return (
<div className="App">
<ChartExample />
</div>
);
}
export default App;
This creates a basic responsive line chart with tooltips and legend.
Understanding the Basics
Recharts provides composable chart components:
- ResponsiveContainer: Makes charts responsive
- LineChart, BarChart, PieChart: Chart type containers
- Line, Bar, Pie: Data series components
- XAxis, YAxis: Axis components
- Tooltip, Legend: Interactive components
- CartesianGrid: Grid lines
Key concepts for advanced usage:
- Composable API: Build charts by composing components
- Data format: Array of objects with consistent keys
- Responsive: Use ResponsiveContainer for automatic sizing
- Customization: Extensive styling and behavior options
- Interactive: Built-in tooltips and legends
Here's an example with multiple chart types:
// src/AdvancedChartExample.jsx
import React from 'react';
import {
LineChart,
BarChart,
PieChart,
Line,
Bar,
Pie,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ResponsiveContainer,
Cell
} from 'recharts';
function AdvancedChartExample() {
const lineData = [
{ name: 'Mon', sales: 120, target: 130 },
{ name: 'Tue', sales: 132, target: 135 },
{ name: 'Wed', sales: 101, target: 110 },
{ name: 'Thu', sales: 134, target: 140 },
{ name: 'Fri', sales: 90, target: 100 }
];
const barData = [
{ name: 'Q1', revenue: 12000 },
{ name: 'Q2', revenue: 15000 },
{ name: 'Q3', revenue: 18000 },
{ name: 'Q4', revenue: 20000 }
];
const pieData = [
{ name: 'Product A', value: 35 },
{ name: 'Product B', value: 28 },
{ name: 'Product C', value: 34 }
];
const COLORS = ['#0088FE', '#00C49F', '#FFBB28'];
return (
<div style={{ padding: '20px', maxWidth: '1200px', margin: '0 auto' }}>
<h2>Advanced Recharts Example</h2>
<div style={{ display: 'flex', flexDirection: 'column', gap: '40px' }}>
<div>
<h3>Line Chart with Multiple Series</h3>
<ResponsiveContainer width="100%" height={300}>
<LineChart data={lineData}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="sales" stroke="#8884d8" />
<Line type="monotone" dataKey="target" stroke="#82ca9d" />
</LineChart>
</ResponsiveContainer>
</div>
<div>
<h3>Bar Chart</h3>
<ResponsiveContainer width="100%" height={300}>
<BarChart data={barData}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
<Bar dataKey="revenue" fill="#8884d8" />
</BarChart>
</ResponsiveContainer>
</div>
<div>
<h3>Pie Chart</h3>
<ResponsiveContainer width="100%" height={300}>
<PieChart>
<Pie
data={pieData}
cx="50%"
cy="50%"
labelLine={false}
label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
outerRadius={80}
fill="#8884d8"
dataKey="value"
>
{pieData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
))}
</Pie>
<Tooltip />
</PieChart>
</ResponsiveContainer>
</div>
</div>
</div>
);
}
export default AdvancedChartExample;
Practical Example / Building Something Real
Let's build a comprehensive analytics dashboard:
// src/AnalyticsDashboard.jsx
import React, { useState } from 'react';
import {
LineChart,
BarChart,
PieChart,
Line,
Bar,
Pie,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ResponsiveContainer,
Cell,
Area,
AreaChart
} from 'recharts';
function AnalyticsDashboard() {
const [selectedPeriod, setSelectedPeriod] = useState('monthly');
const monthlyData = [
{ name: 'Jan', sales: 35, target: 40 },
{ name: 'Feb', sales: 28, target: 35 },
{ name: 'Mar', sales: 34, target: 38 },
{ name: 'Apr', sales: 32, target: 36 },
{ name: 'May', sales: 40, target: 42 },
{ name: 'Jun', sales: 32, target: 38 }
];
const quarterlyData = [
{ name: 'Q1', sales: 97, target: 113 },
{ name: 'Q2', sales: 106, target: 116 },
{ name: 'Q3', sales: 112, target: 120 },
{ name: 'Q4', sales: 120, target: 125 }
];
const revenueData = [
{ name: 'Q1', revenue: 12000 },
{ name: 'Q2', revenue: 15000 },
{ name: 'Q3', revenue: 18000 },
{ name: 'Q4', revenue: 20000 }
];
const categoryData = [
{ name: 'Product A', value: 35 },
{ name: 'Product B', value: 28 },
{ name: 'Product C', value: 34 },
{ name: 'Product D', value: 32 }
];
const currentData = selectedPeriod === 'monthly' ? monthlyData : quarterlyData;
const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];
return (
<div style={{ padding: '20px', maxWidth: '1200px', margin: '0 auto' }}>
<h1>Analytics Dashboard</h1>
<div style={{ marginBottom: '20px', textAlign: 'center' }}>
<button
onClick={() => setSelectedPeriod('monthly')}
style={{
padding: '8px 16px',
margin: '0 5px',
backgroundColor: selectedPeriod === 'monthly' ? '#007bff' : '#6c757d',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
Monthly
</button>
<button
onClick={() => setSelectedPeriod('quarterly')}
style={{
padding: '8px 16px',
margin: '0 5px',
backgroundColor: selectedPeriod === 'quarterly' ? '#007bff' : '#6c757d',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
Quarterly
</button>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '40px' }}>
<div>
<h2>Sales vs Target</h2>
<ResponsiveContainer width="100%" height={400}>
<AreaChart data={currentData}>
<defs>
<linearGradient id="colorSales" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#8884d8" stopOpacity={0.8} />
<stop offset="95%" stopColor="#8884d8" stopOpacity={0} />
</linearGradient>
<linearGradient id="colorTarget" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#82ca9d" stopOpacity={0.8} />
<stop offset="95%" stopColor="#82ca9d" stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
<Area
type="monotone"
dataKey="sales"
stroke="#8884d8"
fillOpacity={1}
fill="url(#colorSales)"
/>
<Area
type="monotone"
dataKey="target"
stroke="#82ca9d"
fillOpacity={1}
fill="url(#colorTarget)"
/>
</AreaChart>
</ResponsiveContainer>
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
<div>
<h2>Quarterly Revenue</h2>
<ResponsiveContainer width="100%" height={400}>
<BarChart data={revenueData}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
<Bar dataKey="revenue" fill="#8884d8" />
</BarChart>
</ResponsiveContainer>
</div>
<div>
<h2>Product Distribution</h2>
<ResponsiveContainer width="100%" height={400}>
<PieChart>
<Pie
data={categoryData}
cx="50%"
cy="50%"
labelLine={false}
label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
outerRadius={100}
fill="#8884d8"
dataKey="value"
>
{categoryData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
))}
</Pie>
<Tooltip />
<Legend />
</PieChart>
</ResponsiveContainer>
</div>
</div>
</div>
</div>
);
}
export default AnalyticsDashboard;
Now create an interactive chart with custom tooltips:
// src/InteractiveChart.jsx
import React, { useState } from 'react';
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ResponsiveContainer
} from 'recharts';
const CustomTooltip = ({ active, payload, label }) => {
if (active && payload && payload.length) {
return (
<div style={{
backgroundColor: '#fff',
border: '1px solid #ccc',
borderRadius: '4px',
padding: '10px'
}}>
<p style={{ margin: 0, fontWeight: 'bold' }}>{`${label}`}</p>
{payload.map((entry, index) => (
<p key={index} style={{ margin: '5px 0', color: entry.color }}>
{`${entry.name}: ${entry.value}`}
</p>
))}
</div>
);
}
return null;
};
function InteractiveChart() {
const [activeIndex, setActiveIndex] = useState(null);
const data = [
{ name: 'Jan', sales: 35, target: 40 },
{ name: 'Feb', sales: 28, target: 35 },
{ name: 'Mar', sales: 34, target: 38 },
{ name: 'Apr', sales: 32, target: 36 },
{ name: 'May', sales: 40, target: 42 },
{ name: 'Jun', sales: 32, target: 38 }
];
return (
<div style={{ padding: '20px', maxWidth: '900px', margin: '0 auto' }}>
<h2>Interactive Chart with Custom Tooltip</h2>
<ResponsiveContainer width="100%" height={500}>
<LineChart
data={data}
onMouseMove={(state) => {
if (state && state.activeTooltipIndex !== undefined) {
setActiveIndex(state.activeTooltipIndex);
}
}}
onMouseLeave={() => setActiveIndex(null)}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip content={<CustomTooltip />} />
<Legend />
<Line
type="monotone"
dataKey="sales"
stroke="#8884d8"
strokeWidth={2}
activeDot={{ r: 8 }}
/>
<Line
type="monotone"
dataKey="target"
stroke="#82ca9d"
strokeWidth={2}
activeDot={{ r: 8 }}
/>
</LineChart>
</ResponsiveContainer>
{activeIndex !== null && (
<div style={{
marginTop: '20px',
padding: '10px',
backgroundColor: '#f8f9fa',
borderRadius: '4px'
}}>
Selected: {data[activeIndex].name} - Sales: {data[activeIndex].sales}, Target: {data[activeIndex].target}
</div>
)}
</div>
);
}
export default InteractiveChart;
Update your App.jsx:
// src/App.jsx
import React from 'react';
import AnalyticsDashboard from './AnalyticsDashboard';
import InteractiveChart from './InteractiveChart';
import './App.css';
function App() {
return (
<div className="App">
<AnalyticsDashboard />
<InteractiveChart />
</div>
);
}
export default App;
This example demonstrates:
- Analytics dashboard
- Multiple chart types
- Interactive features
- Custom tooltips
- Dynamic data updates
- Gradient fills
- Custom styling
Common Issues / Troubleshooting
Chart not displaying: Make sure you're importing components correctly from
'recharts'. Check that the data array is properly formatted.Data format error: Ensure data is an array of objects with consistent keys. All objects should have the same property names.
Responsive not working: Use
ResponsiveContainerto wrap your charts. Set width and height props on ResponsiveContainer.Styling issues: Customize colors through component props. Use
strokefor line colors andfillfor bar/area colors.Tooltip not showing: Add
Tooltipcomponent inside your chart. Customize it with a custom content component if needed.Performance: For large datasets, consider data sampling or pagination. Recharts handles large datasets well, but optimization may be needed for very large datasets.
Next Steps
Now that you have an advanced understanding of Recharts:
- Explore all available chart types
- Learn about advanced configurations
- Implement custom components
- Add animations
- Create real-time updating charts
- Learn about other chart libraries
- Check the official repository: https://github.com/recharts/recharts
Summary
You've successfully integrated Recharts into your React application with advanced features including analytics dashboards, interactive charts, custom tooltips, and gradient visualizations. Recharts provides a powerful, composable solution for creating professional data visualizations with extensive customization options.
SEO Keywords
recharts
React Recharts
recharts tutorial
React data visualization
recharts installation
React chart library
recharts example
React composable charts
recharts setup
React interactive charts
recharts customization
React chart component
recharts dashboard
React D3 charts
recharts getting started
Top comments (0)