The user wants me to create a responsive Tailwind admin dashboard with several specific requirements:
Container-based resizing (charts should respond to their container's resize, not window resize)
Use Chart.js for charts
Implement a ResizeObserver hook
Charts should redraw only when the layout panel actually changes size (e.g., on sidebar toggle)
It should be responsive
I need to create:
A custom React hook using ResizeObserver for container resize detection
An admin dashboard layout with a sidebar
Multiple Chart.js charts that are responsive to their container
Demonstrate the sidebar toggle functionality
Make it all responsive with Tailwind CSS
Let me break down the implementation:
useResizeObserver Hook : A custom hook that observes element resize and provides callback
useChartResize Hook : A specialized hook for charts that handles resize and triggers redraws
Dashboard Layout : With sidebar toggle
Various Charts : Line, Bar, Pie charts as examples
Responsive Grid : That adjusts on sidebar toggle
Here's the complete implementation:
tsx Copy code
// hooks/useResizeObserver.ts
import { useEffect, useRef, useState } from 'react';
export const useResizeObserver = (callback?: (entry: ResizeObserverEntry) => void) => {
const ref = useRef<HTMLDivElement>(null);
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
useEffect(() => {
const element = ref.current;
if (!element) return;
const resizeObserver = new ResizeObserver((entries) => {
for (let entry of entries) {
const { width, height } = entry.contentRect;
setDimensions({ width, height });
callback?.(entry);
}
});
resizeObserver.observe(element);
return () => {
resizeObserver.disconnect();
};
}, [callback]);
return { ref, dimensions };
};
useChartResize Hook : Specialized for Chart.js
tsx Copy code
// hooks/useChartResize.ts
import { useEffect, useRef, useState } from 'react';
import { Chart, ChartConfiguration } from 'chart.js';
export const useChartResize = () => {
const containerRef = useRef<HTMLDivElement>(null);
const chartRef = useRef<Chart | null>(null);
I'm setting up a hook that manages both the container reference and chart instance, allowing the chart to respond when its container dimensions change. The ResizeObserver will trigger chart redraws only when the actual container size shifts, such as when toggling the sidebar.
tsx Copy code
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const resizeObserver = new ResizeObserver((entries) => {
for (let entry of entries) {
const { width, height } = entry.contentRect;
setDimensions({ width, height });
if (chartRef.current) {
chartRef.current.resize();
}
}
});
resizeObserver.observe(container);
return () => {
resizeObserver.disconnect();
};
}, []);
return { containerRef, chartRef, dimensions };
};
Complete Dashboard Component
Responsive Tailwind Admin Dashboard with Container-Based Chart Resizing
I'll create a complete admin dashboard with ResizeObserver-based chart resizing that responds to layout changes.
1. Custom Hooks
typescript Copy code
// hooks/useResizeObserver.ts
import { useEffect, useRef, useCallback } from 'react';
interface ResizeObserverEntry {
contentRect: DOMRectReadOnly;
target: Element;
}
interface ResizeDimensions {
width: number;
height: number;
}
export const useResizeObserver = (
callback?: (dimensions: ResizeDimensions, entry: ResizeObserverEntry) => void
) => {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const element = ref.current;
if (!element) return;
const resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
const { width, height } = entry.contentRect;
callback?.({ width, height }, entry);
}
});
resizeObserver.observe(element);
return () => {
resizeObserver.disconnect();
};
}, [callback]);
return ref;
};
typescript Copy code
// hooks/useChartResize.ts
import { useEffect, useRef, useCallback, useState } from 'react';
import { Chart as ChartJS } from 'chart.js';
interface ChartResizeReturn {
containerRef: React.RefObject<HTMLDivElement>;
chartRef: React.MutableRefObject<ChartJS | null>;
}
export const useChartResize = (): ChartResizeReturn => {
const containerRef = useRef<HTMLDivElement>(null);
const chartRef = useRef<ChartJS | null>(null);
const resizeTimeoutRef = useRef<NodeJS.Timeout>();
const [isResizing, setIsResizing] = useState(false);
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
const { width, height } = entry.contentRect;
// Skip if dimensions are too small (likely a transient state)
if (width < 50 || height < 50) return;
setIsResizing(true);
// Debounce chart resize to avoid excessive redraws
if (resizeTimeoutRef.current) {
clearTimeout(resizeTimeoutRef.current);
}
resizeTimeoutRef.current = setTimeout(() => {
if (chartRef.current) {
// Resize the chart
chartRef.current.resize();
// Optional: redraw the chart
chartRef.current.update('none'); // 'none' = no animation
setIsResizing(false);
}
}, 150);
}
});
resizeObserver.observe(container);
return () => {
resizeObserver.disconnect();
if (resizeTimeoutRef.current) {
clearTimeout(resizeTimeoutRef.current);
}
};
}, []);
return { containerRef, chartRef };
};
typescript Copy code
// hooks/useSidebarToggle.ts
import { useState, useCallback } from 'react';
export const useSidebarToggle = () => {
const [isExpanded, setIsExpanded] = useState(true);
const toggle = useCallback(() => {
setIsExpanded((prev) => !prev);
}, []);
return { isExpanded, toggle };
};
2. Chart Components
typescript Copy code
// components/LineChart.tsx
import React, { useEffect } from 'react';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
ChartOptions,
} from 'chart.js';
import { Line } from 'react-chartjs-2';
import { useChartResize } from '@/hooks/useChartResize';
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
export const LineChart: React.FC = () => {
const { containerRef, chartRef } = useChartResize();
const data = {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
datasets: [
{
label: 'Revenue',
data: [12000, 19000, 3000, 5000, 20000, 30000],
borderColor: 'rgb(59, 130, 246)',
backgroundColor: 'rgba(59, 130, 246, 0.1)',
tension: 0.4,
fill: true,
borderWidth: 2,
pointRadius: 4,
pointBackgroundColor: 'rgb(59, 130, 246)',
pointBorderColor: '#fff',
pointBorderWidth: 2,
},
{
label: 'Expenses',
data: [8000, 15000, 9000, 12000, 18000, 22000],
borderColor: 'rgb(239, 68, 68)',
backgroundColor: 'rgba(239, 68, 68, 0.1)',
tension: 0.4,
fill: true,
borderWidth: 2,
pointRadius: 4,
pointBackgroundColor: 'rgb(239, 68, 68)',
pointBorderColor: '#fff',
pointBorderWidth: 2,
},
],
};
const options: ChartOptions<'line'> = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: true,
position: 'top' as const,
labels: {
usePointStyle: true,
padding: 20,
font: { size: 12 },
},
},
title: {
display: false,
},
tooltip: {
mode: 'index' as const,
intersect: false,
backgroundColor: 'rgba(0, 0, 0, 0.8)',
padding: 12,
borderRadius: 4,
},
},
scales: {
y: {
beginAtZero: true,
grid: {
color: 'rgba(0, 0, 0, 0.05)',
},
},
x: {
grid: {
display: false,
},
},
},
};
return (
<div
ref={containerRef}
className="relative w-full h-80 bg-white rounded-lg shadow-md p-4"
>
<Line ref={chartRef} data={data} options={options} />
<div className="absolute top-2 right-2 text-xs text-gray-400">
Container-based resize
</div>
</div>
);
};
typescript Copy code
// components/BarChart.tsx
import React from 'react';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend,
ChartOptions,
} from 'chart.js';
import { Bar } from 'react-chartjs-2';
import { useChartResize } from '@/hooks/useChartResize';
ChartJS.register(
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend
);
export const BarChart: React.FC = () => {
const { containerRef, chartRef } = useChartResize();
const data = {
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
datasets: [
{
label: 'Sales',
data: [65, 59, 80, 81, 56, 55, 40],
backgroundColor: 'rgba(59, 130, 246, 0.8)',
borderColor: 'rgb(59, 130, 246)',
borderRadius: 4,
borderSkipped: false,
},
{
label: 'Returns',
data: [15, 9, 10, 11, 6, 5, 8],
backgroundColor: 'rgba(239, 68, 68, 0.8)',
borderColor: 'rgb(239, 68, 68)',
borderRadius: 4,
borderSkipped: false,
},
],
};
const options: ChartOptions<'bar'> = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: true,
position: 'top' as const,
labels: {
usePointStyle: true,
padding: 20,
font: { size: 12 },
},
},
tooltip: {
backgroundColor: 'rgba(0, 0, 0, 0.8)',
padding: 12,
borderRadius: 4,
},
},
scales: {
y: {
beginAtZero: true,
grid: {
color: 'rgba(0, 0, 0, 0.05)',
},
},
x: {
grid: {
display: false,
},
},
},
};
return (
<div
ref={containerRef}
className="relative w-full h-80 bg-white rounded-lg shadow-md p-4"
>
<Bar ref={chartRef} data={data} options={options} />
</div>
);
};
typescript Copy code
// components/PieChart.tsx
import React from 'react';
import {
Chart as ChartJS,
ArcElement,
Tooltip,
Legend,
ChartOptions,
} from 'chart.js';
import { Pie } from 'react-chartjs-2';
import { useChartResize } from '@/hooks/useChartResize';
ChartJS.register(ArcElement, Tooltip, Legend);
export const PieChart: React.FC = () => {
const { containerRef, chartRef } = useChartResize();
const data = {
labels: ['Product A', 'Product B', 'Product C', 'Product D'],
datasets: [
{
data: [300, 150, 200, 100],
backgroundColor: [
'rgba(59, 130, 246, 0.8)',
'rgba(34, 197, 94, 0.8)',
'rgba(251, 146, 60, 0.8)',
'rgba(168, 85, 247, 0.8)',
],
borderColor: [
'rgb(59, 130, 246)',
'rgb(34, 197, 94)',
'rgb(251, 146, 60)',
'rgb(168, 85, 247)',
],
borderWidth: 2,
},
],
};
const options: ChartOptions<'pie'> = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: true,
position: 'bottom' as const,
labels: {
padding: 20,
font: { size: 12 },
},
},
tooltip: {
backgroundColor: 'rgba(0, 0, 0, 0.8)',
padding: 12,
borderRadius: 4,
},
},
};
return (
<div
ref={containerRef}
className="relative w-full h-80 bg-white rounded-lg shadow-md p-4"
>
<Pie ref={chartRef} data={data} options={options} />
</div>
);
};
3. Sidebar Component
typescript Copy code
// components/Sidebar.tsx
import React from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
interface SidebarProps {
isExpanded: boolean;
onToggle: () => void;
}
export const Sidebar: React.FC<SidebarProps> = ({ isExpanded, onToggle }) => {
const menuItems = [
{ icon: '📊', label: 'Dashboard', active: true },
{ icon: '📈', label: 'Analytics' },
{ icon: '👥', label: 'Users' },
{ icon: '📋', label: 'Reports' },
{ icon: '⚙️', label: 'Settings' },
];
return (
<aside
className={`${
isExpanded ? 'w-64' : 'w-20'
} bg-slate-900 text-white transition-all duration-300 ease-in-out flex flex-col h-screen shadow-lg`}
>
{/* Header */}
<div className="flex items-center justify-between p-4 border-b border-slate-700">
{isExpanded && (
<h1 className="text-xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-blue-400 to-purple-400">
Admin
</h1>
)}
<button
onClick={onToggle}
className="p-1.5 hover:bg-slate-800 rounded-lg transition-colors"
aria-label="Toggle sidebar"
>
{isExpanded ? (
<ChevronLeft size={20} />
) : (
<ChevronRight size={20} />
)}
</button>
</div>
{/* Menu Items */}
<nav className="flex-1 p-4">
<ul className="space-y-2">
{menuItems.map((item) => (
<li key={item.label}>
<a
href="#"
className={`flex items-center space-x-3 px-4 py-3 rounded-lg transition-all ${
item.active
? 'bg-blue-600 text-white'
: 'text-slate-300 hover:bg-slate-800'
}`}
>
<span className="text-lg">{item.icon}</span>
{isExpanded && <span className="text-sm font-medium">{item.label}</span>}
</a>
</li>
))}
</ul>
</nav>
{/* Footer */}
<div className="p-4 border-t border-slate-700">
<div className="flex items-center space-x-3">
<div className="w-10 h-10 bg-gradient-to-r from-blue-400 to-purple-400 rounded-full"></div>
{isExpanded && (
<div className="flex-1">
<p className="text-sm font-medium">Admin User</p>
<p className="text-xs text-slate-400">admin@example.com</p>
</div>
)}
</div>
</div>
</aside>
);
};
4. Header Component
typescript Copy code
// components/Header.tsx
import React from 'react';
import { Bell, Search, Settings } from 'lucide-react';
export const Header: React.FC = () => {
return (
<header className="bg-white shadow-sm border-b border-gray-200">
<div className="flex items-center justify-between px-6 py-4">
<div className="flex-1 max-w-md">
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
<input
type="text"
placeholder="Search..."
className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none transition"
/>
</div>
</div>
<div className="flex items-center space-x-6 ml-auto">
<button className="relative p-2 text-gray-600 hover:text-gray-900 transition">
<Bell size={20} />
<span className="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full"></span>
</button>
<button className="p-2 text-gray-600 hover:text-gray-900 transition">
<Settings size={20} />
</button>
</div>
</div>
</header>
);
};
5. Stats Card Component
typescript Copy code
// components/StatsCard.tsx
import React from 'react';
import { TrendingUp, TrendingDown } from 'lucide-react';
interface StatsCardProps {
title: string;
value: string;
change: number;
icon: React.ReactNode;
color: 'blue' | 'green' | 'purple' | 'orange';
}
export const StatsCard: React.FC<StatsCardProps> = ({
title,
value,
change,
icon,
color,
}) => {
const colorClasses = {
blue: 'bg-blue-50 text-blue-600',
green: 'bg-green-50 text-green-600',
purple: 'bg-purple-50 text-purple-600',
orange: 'bg-orange-50 text-orange-600',
};
const isPositive = change >= 0;
return (
<div className="bg-white rounded-lg shadow-md p-6 hover:shadow-lg transition-shadow">
<div className="flex items-start justify-between">
<div>
<p className="text-gray-600 text-sm font-medium">{title}</p>
<p className="text-2xl font-bold mt-2 text-gray-900">{value}</p>
<div className="flex items-center mt-2">
{isPositive ? (
<TrendingUp className="text-green-500" size={16} />
) : (
<TrendingDown className="text-red-500" size={16} />
)}
<span
className={`ml-1 text-sm font-medium ${
isPositive ? 'text-green-500' : 'text-red-500'
}`}
>
{isPositive ? '+' : ''}{change}%
</span>
</div>
</div>
<div className={`p-3 rounded-lg ${colorClasses[color]}`}>
{icon}
</div>
</div>
</div>
);
};
6. Main Dashboard
7. Alternative: Enhanced useChartResize with Multiple Chart Types
typescript Copy code
// hooks/useAdvancedChartResize.ts
import { useEffect, useRef, useCallback, useReducer } from 'react';
import { Chart as ChartJS } from 'chart.js';
interface ResizeState {
isResizing: boolean;
width: number;
height: number;
resizeCount: number;
}
type ResizeAction =
| { type: 'START_RESIZE'; width: number; height: number }
| { type: 'END_RESIZE' }
| { type: 'RESET' };
export const useAdvancedChartResize = () => {
const containerRef = useRef<HTMLDivElement>(null);
const chartRef = useRef<ChartJS | null>(null);
const resizeTimeoutRef = useRef<NodeJS.Timeout>();
const observerRef = useRef<ResizeObserver | null>(null);
const [state, dispatch] = useReducer(
(state: ResizeState, action: ResizeAction): ResizeState => {
switch (action.type) {
case 'START_RESIZE':
return {
...state,
isResizing: true,
width: action.width,
height: action.height,
resizeCount: state.resizeCount + 1,
};
case 'END_RESIZE':
return { ...state, isResizing: false };
case 'RESET':
return { isResizing: false, width: 0, height: 0, resizeCount: 0 };
default:
return state;
}
},
{ isResizing: false, width: 0, height: 0, resizeCount: 0 }
);
const handleResize = useCallback(() => {
if (chartRef.current) {
chartRef.current.resize();
chartRef.current.update('none');
dispatch({ type: 'END_RESIZE' });
}
}, []);
useEffect(() => {
const container = containerRef.current;
if (!container) return;
observerRef.current = new ResizeObserver((entries) => {
for (const entry of entries) {
const { width, height } = entry.contentRect;
// Only trigger for meaningful size changes
if (width > 0 && height > 0) {
dispatch({
type: 'START_RESIZE',
width,
height,
});
if (resizeTimeoutRef.current) {
clearTimeout(resizeTimeoutRef.current);
}
resizeTimeoutRef.current = setTimeout(handleResize, 200);
}
}
});
observerRef.current.observe(container);
return () => {
observerRef.current?.disconnect();
if (resizeTimeoutRef.current) {
clearTimeout(resizeTimeoutRef.current);
}
};
}, [handleResize]);
return { containerRef, chartRef, state };
};
8. Package.json Dependencies
json Copy code
{
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"chart.js": "^4.4.0",
"react-chartjs-2": "^5.2.0",
"lucide-react": "^0.294.0"
},
"devDependencies": {
"typescript": "^5.3.0",
"tailwindcss": "^3.3.0",
"@types/react": "^18.2.0",
"@types/node": "^20.10.0"
}
}
Key Features Explained
🎯 Container-Based Resizing
ResizeObserver API : Monitors actual container size changes
Not window-based : Charts respond to their specific container, not window resize
Independent : Each chart independently detects its container changes
⚡ Performance Optimizations
typescript Copy code
// Debounced resize handling (150-200ms)
resizeTimeoutRef.current = setTimeout(() => {
if (chartRef.current) {
chartRef.current.resize();
chartRef.current.update('none'); // No animation on resize
}
}, 150);
📊 Responsive Grid System
Uses Tailwind Grid: grid-cols-1 md:grid-cols-2 lg:grid-cols-4
Charts automatically reflow when sidebar toggles
Container dimensions trigger chart redraws
🎨 Smooth Transitions
typescript Copy code
// Sidebar smooth collapse/expand
<div className="transition-all duration-300 ease-in-out">
<Sidebar isExpanded={isExpanded} onToggle={toggle} />
</div>
✨ Advanced Features
Debounced Resize Events : Prevents excessive redraws
State Management : Tracks resize state and count
Error Handling : Safely checks for null references
Memory Leak Prevention : Proper cleanup in useEffect
This implementation provides a production-ready dashboard with intelligent, container-aware chart resizing!