Certainly! Below is a React component built with Next.js 14, TypeScript, and TailwindCSS that fulfills your requirements. This ResponsiveWrapper component dynamically displays child components in a wrapping fashion with space-between behavior for each row. It accepts a child component, an array of properties to feed into the child component, a key prefix for unique keys, and a responsive configuration for the number of items per row based on TailwindCSS breakpoints.
Component Features:
- Responsive Layout: Utilizes the
useScreenWidth hook to determine the current breakpoint and adjust the number of items per row accordingly.
- Dynamic Rendering: Maps through the
propsArray to render the child components with the provided properties.
- Flexbox Layout: Uses Flexbox with
justify-between to ensure space-between behavior in each row.
- TailwindCSS Styling: Applies a default
gap-8 for both row and column gaps and dynamically adjusts child widths based on the number of items per row.
Implementation:
// components/ResponsiveWrapper.tsx
import React from 'react';
import { ReactElement, ComponentType } from 'react';
import useScreenWidth, { Breakpoint } from '../hooks/useScreenWidth';
interface ResponsiveWrapperProps<P> {
ChildComponent: ComponentType<P>;
propsArray: P[];
keyPrefix: string;
itemsPerRow: Partial<Record<Breakpoint, number>>;
}
const breakpointOrder: Breakpoint[] = ['base', 'sm', 'md', 'lg', 'xl', '2xl'];
const ResponsiveWrapper = <P,>({
ChildComponent,
propsArray,
keyPrefix,
itemsPerRow,
}: ResponsiveWrapperProps<P>): ReactElement => {
const currentBreakpoint = useScreenWidth();
// Determine the current number of items per row based on breakpoint
const getItemsPerRow = (): number => {
// Start from the current breakpoint and move down to find the applicable value
const currentIndex = breakpointOrder.indexOf(currentBreakpoint);
for (let i = currentIndex; i >= 0; i--) {
const bp = breakpointOrder[i];
if (itemsPerRow[bp]) {
return itemsPerRow[bp] as number;
}
}
// Fallback to 1 if not specified
return 1;
};
const itemsPerCurrentRow = getItemsPerRow();
// Helper function to chunk the propsArray
const chunkArray = (array: P[], chunkSize: number): P[][] => {
const chunks: P[][] = [];
for (let i = 0; i < array.length; i += chunkSize) {
chunks.push(array.slice(i, i + chunkSize));
}
return chunks;
};
const rows = chunkArray(propsArray, itemsPerCurrentRow);
// Determine the width class for child components based on itemsPerRow
const getWidthClasses = (): string => {
const classes: string[] = [];
breakpointOrder.forEach((bp) => {
const count = itemsPerRow[bp];
if (count) {
let widthClass = '';
switch (count) {
case 1:
widthClass = 'w-full';
break;
case 2:
widthClass = 'w-1/2';
break;
case 3:
widthClass = 'w-1/3';
break;
case 4:
widthClass = 'w-1/4';
break;
case 5:
widthClass = 'w-1/5';
break;
case 6:
widthClass = 'w-1/6';
break;
default:
widthClass = `w-${Math.floor((100 / count) * 10) / 10}/12`; // Approximation
}
if (bp === 'base') {
classes.push(widthClass);
} else {
classes.push(`${bp}:${widthClass}`);
}
}
});
return classes.join(' ');
};
const childWidthClasses = getWidthClasses();
return (
<div className="flex flex-col gap-y-8">
{rows.map((rowProps, rowIndex) => (
<div
key={`${keyPrefix}-row-${rowIndex}`}
className="flex justify-between gap-x-8"
>
{rowProps.map((props, index) => (
<div
key={`${keyPrefix}-${rowIndex}-${index}`}
className={childWidthClasses}
>
<ChildComponent {...props} />
</div>
))}
</div>
))}
</div>
);
};
export default ResponsiveWrapper;
Explanation:
-
Props Interface:
ChildComponent: The React component to be rendered multiple times.
propsArray: An array of props to be passed to each instance of the child component.
keyPrefix: A string to prefix each key for uniqueness.
itemsPerRow: An object mapping TailwindCSS breakpoints to the number of items per row.
-
Breakpoint Handling:
- The
useScreenWidth hook determines the current breakpoint.
- The
getItemsPerRow function traverses the breakpoints from the current one downwards to find the applicable itemsPerRow value.
-
Chunking Props:
- The
chunkArray function splits the propsArray into smaller arrays based on the number of items per row.
-
Dynamic Width Classes:
- The
getWidthClasses function generates TailwindCSS width classes based on the itemsPerRow prop. For example, if itemsPerRow = { base: 1, md: 2 }, it will generate w-full md:w-1/2.
-
Rendering:
- The component renders each row as a flex container with
justify-between to ensure space-between behavior.
- Each child component is wrapped in a
div with the appropriate width classes.
Example Usage:
Assuming you have a child component named Card and a useScreenWidth hook, here's how you can use the ResponsiveWrapper:
// components/Card.tsx
import React from 'react';
interface CardProps {
title: string;
description: string;
}
const Card: React.FC<CardProps> = ({ title, description }) => (
<div className="border rounded p-4 shadow">
<h3 className="text-lg font-semibold">{title}</h3>
<p className="text-gray-600">{description}</p>
</div>
);
export default Card;
// hooks/useScreenWidth.ts
import { useState, useEffect } from 'react';
export type Breakpoint = 'base' | 'sm' | 'md' | 'lg' | 'xl' | '2xl';
const breakpoints: Record<Breakpoint, number> = {
base: 0,
sm: 640,
md: 768,
lg: 1024,
xl: 1280,
'2xl': 1536,
};
const useScreenWidth = (): Breakpoint => {
const [width, setWidth] = useState<number>(0);
const [breakpoint, setBreakpoint] = useState<Breakpoint>('base');
useEffect(() => {
const handleResize = () => {
const currentWidth = window.innerWidth;
setWidth(currentWidth);
const matchedBreakpoint: Breakpoint = Object.keys(breakpoints)
.filter((bp) => currentWidth >= breakpoints[bp as Breakpoint])
.pop() as Breakpoint;
setBreakpoint(matchedBreakpoint);
};
handleResize(); // Initialize
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return breakpoint;
};
export default useScreenWidth;
// pages/index.tsx
import React from 'react';
import ResponsiveWrapper from '../components/ResponsiveWrapper';
import Card from '../components/Card';
const cardData = [
{ title: 'Card 1', description: 'Description for Card 1' },
{ title: 'Card 2', description: 'Description for Card 2' },
{ title: 'Card 3', description: 'Description for Card 3' },
{ title: 'Card 4', description: 'Description for Card 4' },
{ title: 'Card 5', description: 'Description for Card 5' },
{ title: 'Card 6', description: 'Description for Card 6' },
];
const HomePage: React.FC = () => {
return (
<div className="p-8">
<ResponsiveWrapper
ChildComponent={Card}
propsArray={cardData}
keyPrefix="card"
itemsPerRow={{ base: 1, md: 2, xl: 3 }}
/>
</div>
);
};
export default HomePage;
TailwindCSS Configuration:
Ensure that your tailwind.config.js includes all necessary breakpoints:
// tailwind.config.js
module.exports = {
theme: {
screens: {
sm: '640px',
md: '768px',
lg: '1024px',
xl: '1280px',
'2xl': '1536px',
},
// ... other configurations
},
// ... other configurations
};
Additional Notes:
- Flexbox vs. Grid: This implementation uses Flexbox to achieve the space-between behavior for each row. If you prefer using CSS Grid, adjustments would be necessary.
- Dynamic Width Classes: The
getWidthClasses function can be extended to handle more complex scenarios or additional breakpoints.
- Performance Considerations: For large datasets, consider optimizing the chunking logic or implementing virtualization.
This ResponsiveWrapper component should provide a flexible and responsive layout for your child components, adhering to modern best practices with React, TypeScript, Next.js, and TailwindCSS.