You are an expert software engineer specialised in Next.js 14 with TypeScript. I am using TailwindCSS for styling. You utilise or modern techniques and best practices in crafting your solutions. I need you to build me a component that allows me to display children components in a wrapping fashion while ensuring space-between behaviour for each row. It takes in two inputs, the child component which will be displayed, and an array of properties which will be fed into the child component using destructive means, and finally a keyPrefix to allow for unique definition of keys. There is also an input whereby I specify the number of children component in each row. The purpose of this is to be responsive depending on the screen width. It takes in TailwindCSS breakpoints. For example, if I specify base as 1, and “md” as 2, and “xl” as 3, then it means for sizes below “md” each row will have one child component. for sizes above “md” and up to “xl” breakpoint, there will be two children component. And above “xl”, there will be three children components. Use my useScreenWidth hook where necessary. Specify the default gap as gap-8 both between rows and between children components. However, by children components are justified between (spaced between). Program your solution in this file components/c-ui/container.tsx.
Code Implementations:
hooks/screen-width.hook.ts
tsx
Assistant
// hooks/useTailwindScreen.ts
import { useState, useEffect } from "react";
/**
* TailwindCSS default breakpoints in pixels.
*/
const tailwindBreakpoints: Record<string, number> = { sm: 640, md: 768, lg: 1024, xl: 1280, "2xl": 1536 };
/**
* Sorted array of breakpoint names based on their min-width.
*/
const sortedBreakpoints = Object.keys(tailwindBreakpoints).sort((a, b) => tailwindBreakpoints[a] - tailwindBreakpoints[b]) as Array<
keyof typeof tailwindBreakpoints
>;
/**
* Custom hook to determine if the current screen size matches a TailwindCSS breakpoint.
*
* @param size - The TailwindCSS breakpoint to check (e.g., 'sm', 'md', 'lg', etc.).
* @param strict - If true, the hook checks if the screen width is within the exact range of the breakpoint.
* If false, it checks if the screen width is equal to or greater than the breakpoint's min-width.
* Defaults to false.
* @returns A boolean indicating whether the current screen size matches the criteria.
*/
function useScreenWidth(size: keyof typeof tailwindBreakpoints, strict: boolean = false): boolean {
const [matches, setMatches] = useState<boolean>(false);
useEffect(() => {
if (typeof window === "undefined") {
// If window is undefined (e.g., during SSR), default to false
return;
}
const minWidth = tailwindBreakpoints[size];
let maxWidth: number | undefined;
if (strict) {
const currentIndex = sortedBreakpoints.indexOf(size);
if (currentIndex === -1) {
console.warn(`Invalid Tailwind breakpoint: ${size}`);
return;
}
if (currentIndex < sortedBreakpoints.length - 1) {
const nextSize = sortedBreakpoints[currentIndex + 1];
maxWidth = tailwindBreakpoints[nextSize] - 1;
}
}
let query = `(min-width: ${minWidth}px)`;
if (strict && maxWidth !== undefined) {
query += ` and (max-width: ${maxWidth}px)`;
}
const mediaQueryList = window.matchMedia(query);
const updateMatch = (event: MediaQueryListEvent) => {
setMatches(event.matches);
};
// Initial check
setMatches(mediaQueryList.matches);
// Add listener using modern `addEventListener`
mediaQueryList.addEventListener("change", updateMatch);
// Cleanup listener on unmount
return () => {
mediaQueryList.removeEventListener("change", updateMatch);
};
}, [size, strict]);
return matches;
}
export default useScreenWidth;
Certainly! Below is the implementation of the ResponsiveContainer component as per your specifications. This component dynamically adjusts the number of child components displayed per row based on the current screen width, utilizing TailwindCSS for styling and your custom useScreenWidth hook for responsiveness.
Overview
Props Definition:
ChildComponent: The React component to be rendered multiple times.
items: An array of properties that will be spread into each ChildComponent instance.
keyPrefix: A string prefix to ensure unique keys for each child.
childrenPerRow: An object defining the number of children per row for different TailwindCSS breakpoints.
Breakpoint Detection:
Utilizes the useScreenWidth hook to determine the current active breakpoint.
Checks from the largest breakpoint to the smallest to identify which one matches the current screen width.
Rendering Logic:
Based on the active breakpoint, determines how many child components should be displayed per row.
Splits the items array into chunks corresponding to the number of children per row.
Renders each chunk in a flex container with justify-between and gap-8, ensuring space-between behavior and consistent gaps.
Styling:
Applies TailwindCSS classes to manage layout and spacing.
Ensures responsiveness by adapting the layout based on the detected breakpoint.
Implementation
Create the ResponsiveContainer component in components/c-ui/container.tsx as follows:
tsx
// components/c-ui/container.tsx
import React from 'react';
import useScreenWidth from '../../hooks/useTailwindScreen'; // Adjust the path as necessary
type Breakpoint = 'base' | 'sm' | 'md' | 'lg' | 'xl' | '2xl';
interface ChildrenPerRow {
base?: number;
sm?: number;
md?: number;
lg?: number;
xl?: number;
'2xl'?: number;
}
interface ResponsiveContainerProps<P> {
ChildComponent: React.ComponentType<P>;
items: P[];
keyPrefix: string;
childrenPerRow: ChildrenPerRow;
}
const ResponsiveContainer = <P extends {}>({
ChildComponent,
items,
keyPrefix,
childrenPerRow,
}: ResponsiveContainerProps<P>) => {
// Determine current active breakpoint
const is2xl = useScreenWidth('2xl');
const isxl = useScreenWidth('xl');
const islg = useScreenWidth('lg');
const ismd = useScreenWidth('md');
const issm = useScreenWidth('sm');
const isbase = true; // base is always true
// Determine number of children per row based on the current breakpoint
let currentBreakpoint: Breakpoint = 'base';
if (is2xl) {
currentBreakpoint = '2xl';
} else if (isxl) {
currentBreakpoint = 'xl';
} else if (islg) {
currentBreakpoint = 'lg';
} else if (ismd) {
currentBreakpoint = 'md';
} else if (issm) {
currentBreakpoint = 'sm';
} else {
currentBreakpoint = 'base';
}
const numPerRow =
childrenPerRow[currentBreakpoint] ??
childrenPerRow['base'] ??
1; // Default to 1 if not specified
// Function to split items into chunks based on numPerRow
const chunkArray = (arr: P[], size: number): P[][] => {
const chunks: P[][] = [];
for (let i = 0; i < arr.length; i += size) {
chunks.push(arr.slice(i, i + size));
}
return chunks;
};
const rows = chunkArray(items, numPerRow);
return (
<div className="flex flex-col gap-8">
{rows.map((rowItems, rowIndex) => (
<div
key={`${keyPrefix}-row-${rowIndex}`}
className="flex justify-between gap-x-8"
>
{rowItems.map((item, itemIndex) => (
<ChildComponent
key={`${keyPrefix}-${rowIndex}-${itemIndex}`}
{...item}
/>
))}
</div>
))}
</div>
);
};
export default ResponsiveContainer;
Explanation
Imports and Type Definitions:
React: Necessary for creating the component.
useScreenWidth: Your custom hook for detecting screen width.
Breakpoint: Defines the possible TailwindCSS breakpoints.
ChildrenPerRow: An interface representing the number of children per row for each breakpoint.
ResponsiveContainerProps: Generic interface for the component's props.
Breakpoint Detection:
The component uses the useScreenWidth hook to check each breakpoint, starting from the largest (2xl) to the smallest (sm).
isbase is always true since it represents the default breakpoint.
Determining Current Breakpoint:
The component sequentially checks each breakpoint to find the highest one that matches the current screen width.
Sets currentBreakpoint accordingly.
Calculating Number of Children per Row:
Retrieves the number of children to display per row based on the currentBreakpoint.
Falls back to the base value or defaults to 1 if not specified.
Chunking the Items:
The chunkArray function splits the items array into smaller arrays (rows) based on numPerRow.
Rendering the Rows and Children:
The component renders a flex container (flex flex-col gap-8) that stacks each row vertically with a gap of 8.
Each row is a flex container (flex justify-between gap-x-8) that distributes its children with space between them and a horizontal gap of 8.
Each ChildComponent is rendered with its respective props and a unique key constructed using the keyPrefix, rowIndex, and itemIndex.
Usage Example
Here's how you can use the ResponsiveContainer component in your application:
tsx
// Example usage in a page or another component
import React from 'react';
import ResponsiveContainer from '../components/c-ui/container';
import YourChildComponent from '../components/YourChildComponent';
interface YourChildProps {
title: string;
description: string;
}
const items: YourChildProps[] = [
{ title: 'Item 1', description: 'Description 1' },
{ title: 'Item 2', description: 'Description 2' },
{ title: 'Item 3', description: 'Description 3' },
// Add more items as needed
];
const ExamplePage = () => {
return (
<div className="p-4">
<ResponsiveContainer
ChildComponent={YourChildComponent}
items={items}
keyPrefix="example"
childrenPerRow={{ base: 1, md: 2, xl: 3 }}
/>
</div>
);
};
export default ExamplePage;
Notes
TailwindCSS Breakpoints: Ensure that your TailwindCSS configuration matches the breakpoints used in the useScreenWidth hook.
Performance Consideration: The component uses multiple instances of the useScreenWidth hook. While this is manageable for a limited number of breakpoints, consider optimizing if you have a large number of breakpoints or performance issues.
Accessibility: Ensure that the ChildComponent handles accessibility concerns, especially when dynamically rendering multiple instances.
Feel free to customize the component further based on your specific requirements!