Charts & Analytics

Visualize data beautifully in Next.js

📊 What are Charts & Analytics?

Charts and analytics help visualize data through interactive graphs, dashboards, and metrics. Next.js supports powerful charting libraries like Recharts, Chart.js, and Tremor for creating beautiful, responsive data visualizations that enhance user understanding.


// Simple chart with Recharts
import { LineChart, Line, XAxis, YAxis } from 'recharts'

const data = [
  { name: 'Jan', sales: 400 },
  { name: 'Feb', sales: 300 },
  { name: 'Mar', sales: 600 }
]

<LineChart width={400} height={200} data={data}>
  <Line type="monotone" dataKey="sales" stroke="#8884d8" />
  <XAxis dataKey="name" />
  <YAxis />
</LineChart>
                                    

Key Chart Types

📈

Line Charts

Show trends over time

<LineChart data={data}>
  <Line dataKey="value" />
</LineChart>
📊

Bar Charts

Compare categories

<BarChart data={data}>
  <Bar dataKey="value" />
</BarChart>
🥧

Pie Charts

Show proportions

<PieChart>
  <Pie data={data} />
</PieChart>
📉

Area Charts

Display volume trends

<AreaChart data={data}>
  <Area dataKey="value" />
</AreaChart>

🔹 Setup Recharts in Next.js

Recharts is a composable charting library built on React components. It's perfect for Next.js with responsive design, customizable styling, and excellent TypeScript support for data visualization.

# Install Recharts
npm install recharts
// components/SalesChart.jsx
'use client'
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts'

const data = [
  { month: 'Jan', sales: 4000, revenue: 2400 },
  { month: 'Feb', sales: 3000, revenue: 1398 },
  { month: 'Mar', sales: 2000, revenue: 9800 },
  { month: 'Apr', sales: 2780, revenue: 3908 },
  { month: 'May', sales: 1890, revenue: 4800 },
  { month: 'Jun', sales: 2390, revenue: 3800 }
]

export default function SalesChart() {
  return (
    <ResponsiveContainer width="100%" height={300}>
      <LineChart data={data}>
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="month" />
        <YAxis />
        <Tooltip />
        <Legend />
        <Line type="monotone" dataKey="sales" stroke="#8884d8" />
        <Line type="monotone" dataKey="revenue" stroke="#82ca9d" />
      </LineChart>
    </ResponsiveContainer>
  )
}

Output:

Sales & Revenue Chart

🔹 Bar Chart Example

Bar charts are ideal for comparing values across categories. Use them for sales comparisons, survey results, or any categorical data that needs visual comparison.

// components/ProductChart.jsx
'use client'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts'

const data = [
  { product: 'Product A', sales: 4000 },
  { product: 'Product B', sales: 3000 },
  { product: 'Product C', sales: 2000 },
  { product: 'Product D', sales: 2780 },
  { product: 'Product E', sales: 1890 }
]

export default function ProductChart() {
  return (
    <ResponsiveContainer width="100%" height={300}>
      <BarChart data={data}>
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="product" />
        <YAxis />
        <Tooltip />
        <Legend />
        <Bar dataKey="sales" fill="#8884d8" />
      </BarChart>
    </ResponsiveContainer>
  )
}

🔹 Pie Chart for Proportions

Pie charts display data as proportions of a whole. Perfect for showing market share, budget allocation, or any data where percentages matter more than absolute values.

// components/MarketShareChart.jsx
'use client'
import { PieChart, Pie, Cell, ResponsiveContainer, Legend, Tooltip } from 'recharts'

const data = [
  { name: 'Product A', value: 400 },
  { name: 'Product B', value: 300 },
  { name: 'Product C', value: 300 },
  { name: 'Product D', value: 200 }
]

const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042']

export default function MarketShareChart() {
  return (
    <ResponsiveContainer width="100%" height={300}>
      <PieChart>
        <Pie
          data={data}
          cx="50%"
          cy="50%"
          labelLine={false}
          label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
          outerRadius={80}
          fill="#8884d8"
          dataKey="value"
        >
          {data.map((entry, index) => (
            <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
          ))}
        </Pie>
        <Tooltip />
        <Legend />
      </PieChart>
    </ResponsiveContainer>
  )
}

🔹 Dashboard with Multiple Charts

Combine multiple charts to create comprehensive analytics dashboards. Display key metrics, trends, and comparisons in a single view for better data insights and decision making.

// app/dashboard/page.jsx
'use client'
import SalesChart from '@/components/SalesChart'
import ProductChart from '@/components/ProductChart'
import MarketShareChart from '@/components/MarketShareChart'

export default function Dashboard() {
  return (
    <div className="p-6">
      <h1 className="text-3xl font-bold mb-6">Analytics Dashboard</h1>
      
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div className="bg-white p-4 rounded-lg shadow">
          <h2 className="text-xl font-semibold mb-4">Sales Trend</h2>
          <SalesChart />
        </div>

        <div className="bg-white p-4 rounded-lg shadow">
          <h2 className="text-xl font-semibold mb-4">Product Performance</h2>
          <ProductChart />
        </div>

        <div className="bg-white p-4 rounded-lg shadow">
          <h2 className="text-xl font-semibold mb-4">Market Share</h2>
          <MarketShareChart />
        </div>

        <div className="bg-white p-4 rounded-lg shadow">
          <h2 className="text-xl font-semibold mb-4">Key Metrics</h2>
          <div className="space-y-4">
            <div>
              <p className="text-gray-600">Total Revenue</p>
              <p className="text-2xl font-bold">$24,500</p>
            </div>
            <div>
              <p className="text-gray-600">Total Sales</p>
              <p className="text-2xl font-bold">1,234</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

🔹 Real-time Data Updates

Update charts with real-time data using React state and intervals. Perfect for live dashboards, monitoring systems, or any application requiring dynamic data visualization.

// components/LiveChart.jsx
'use client'
import { useState, useEffect } from 'react'
import { LineChart, Line, XAxis, YAxis, ResponsiveContainer } from 'recharts'

export default function LiveChart() {
  const [data, setData] = useState([
    { time: '0s', value: 0 }
  ])

  useEffect(() => {
    const interval = setInterval(() => {
      setData(prev => {
        const newData = [...prev, {
          time: `${prev.length}s`,
          value: Math.floor(Math.random() * 100)
        }]
        // Keep only last 10 data points
        return newData.slice(-10)
      })
    }, 1000)

    return () => clearInterval(interval)
  }, [])

  return (
    <div>
      <h2>Live Data Stream</h2>
      <ResponsiveContainer width="100%" height={200}>
        <LineChart data={data}>
          <XAxis dataKey="time" />
          <YAxis />
          <Line type="monotone" dataKey="value" stroke="#8884d8" />
        </LineChart>
      </ResponsiveContainer>
    </div>
  )
}

🧠 Test Your Knowledge

Which chart type is best for showing trends over time?