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). I also will input an invisible component which you will use to fill in the remaining empty spots on a row. For example, if the row has a capacity for three children components, and there’s only two children components, one invisible component will be added. The invisible component will have the same sizing as the parent component to make sure spacing is done correctly. Program your solution in this file components/c-ui/container.tsx.
Code Implementations:
hooks/screen-width.hook.ts
tsx
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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 arranges child components into rows based on the current screen width, utilizing TailwindCSS for styling and the provided useScreenWidth hook to determine the active breakpoint.
Overview
Purpose: To display child components in a responsive, wrapping layout with space-between behavior for each row.
Inputs:
ChildComponent: The React component to be rendered as children.
propsArray: An array of props objects to be passed to each ChildComponent.
keyPrefix: A string prefix to generate unique keys for each rendered component.
breakpoints: An object mapping TailwindCSS breakpoints to the number of children per row (e.g., { base: 1, md: 2, xl: 3 }).
Features:
Responsive layout based on specified breakpoints.
Inserts invisible components to fill remaining spots in a row, ensuring consistent spacing.
Utilizes gap-8 for both row gaps and gaps between child components.
Employs modern React practices with TypeScript for type safety.
Implementation
1. Define the ResponsiveContainer Component
Create a new file at components/c-ui/container.tsx and add the following code:
tsx
// components/c-ui/container.tsx
import React from 'react';
import useScreenWidth from '../../hooks/screen-width.hook';
/**
* Defines the possible breakpoints including 'base'.
*/
interface BreakpointDefinitions {
base: number; // Required: Number of children per row for the base breakpoint
sm?: number;
md?: number;
lg?: number;
xl?: number;
'2xl'?: number;
}
type Breakpoint = keyof BreakpointDefinitions;
/**
* Props for the ResponsiveContainer component.
*
* @template P - The type of props for the ChildComponent.
*/
interface ResponsiveContainerProps<P> {
/** The child component to be rendered in the container */
ChildComponent: React.ComponentType<P>;
/** An array of props to pass to each ChildComponent */
propsArray: P[];
/** A prefix string to generate unique keys for each child */
keyPrefix: string;
/**
* An object mapping TailwindCSS breakpoints to the number of children per row.
* Example: { base: 1, md: 2, xl: 3 }
*/
breakpoints: BreakpointDefinitions;
}
/**
* TailwindCSS default breakpoints in pixels.
*/
const tailwindBreakpoints: Record<Breakpoint, number> = {
base: 0, // Base does not have a min-width
sm: 640,
md: 768,
lg: 1024,
xl: 1280,
'2xl': 1536,
};
/**
* The ResponsiveContainer component arranges child components into responsive rows.
*
* @template P - The type of props for the ChildComponent.
*/
const ResponsiveContainer = <P,>({
ChildComponent,
propsArray,
keyPrefix,
breakpoints,
}: ResponsiveContainerProps<P>) => {
// Extract breakpoints excluding 'base' and sort them descendingly by min-width
const breakpointNamesDesc = Object.keys(breakpoints)
.filter((bp) => bp !== 'base') // Exclude 'base' for individual handling
.sort((a, b) => tailwindBreakpoints[b as Breakpoint] - tailwindBreakpoints[a as Breakpoint]) as Exclude<Breakpoint, 'base'>[];
// Use the useScreenWidth hook for each breakpoint to determine if it matches
const breakpointMatches = breakpointNamesDesc.map((bp) => useScreenWidth(bp as Breakpoint, true));
/**
* Determine the current number of children per row based on active breakpoints.
* The first matching breakpoint from largest to smallest determines the perRow count.
* If no breakpoints match, fall back to the 'base' value.
*/
let perRow = breakpoints.base; // Default to 'base' value
for (let i = 0; i < breakpointNamesDesc.length; i++) {
if (breakpointMatches[i]) {
perRow = breakpoints[breakpointNamesDesc[i] as Breakpoint]!; // Non-null assertion as the key exists
break; // Stop at the first matching breakpoint
}
}
// Split the propsArray into rows based on the determined perRow count
const rows: P[][] = [];
for (let i = 0; i < propsArray.length; i += perRow) {
rows.push(propsArray.slice(i, i + perRow));
}
return (
<div className="space-y-8">
{rows.map((row, rowIndex) => {
const missing = perRow - row.length; // Calculate missing components in the row
const children = row.map((childProps, childIndex) => (
<ChildComponent
key={`${keyPrefix}-${rowIndex}-${childIndex}`}
{...childProps}
/>
));
// Add invisible components to fill the remaining spots in the row
for (let i = 0; i < missing; i++) {
children.push(
<div
key={`${keyPrefix}-${rowIndex}-empty-${i}`}
className="invisible flex-1"
/>
);
}
return (
<div
key={`${keyPrefix}-row-${rowIndex}`}
className="flex justify-between gap-8"
>
{children}
</div>
);
})}
</div>
);
};
export default ResponsiveContainer;
2. Explanation of the Implementation
Breakpoint Handling:
The component first filters out the 'base' breakpoint and sorts the remaining breakpoints in descending order based on their min-width values. This ensures that the largest applicable breakpoint is checked first.
It then uses the useScreenWidth hook to determine which breakpoint is currently active.
The perRow variable is set based on the first matching breakpoint. If no breakpoints match (i.e., for screen widths smaller than any defined breakpoints), it falls back to the 'base' value.
Row Construction:
The propsArray is split into multiple rows, each containing perRow number of child components.
For each row, if the number of child components is less than perRow, invisible <div> elements are added to fill the remaining spaces. These invisible components have the invisible and flex-1 classes to occupy space without being visible, ensuring consistent spacing.
Styling with TailwindCSS:
The main container uses space-y-8 to apply a vertical gap of 8 between each row.
Each row uses flex, justify-between, and gap-8 to arrange child components with space-between behavior and a horizontal gap of 8.
Invisible components within rows are styled with invisible and flex-1 to maintain the layout without displaying any content.
3. Usage Example
Here's how you can utilize 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 MyChildComponent from '../components/MyChildComponent';
const childPropsArray = [
{ /* props for first child */ },
{ /* props for second child */ },
// ...more props
];
const MyPage = () => {
return (
<ResponsiveContainer
ChildComponent={MyChildComponent}
propsArray={childPropsArray}
keyPrefix="my-page-container"
breakpoints={{
base: 1,
md: 2,
xl: 3,
}}
/>
);
};
export default MyPage;
In this example:
MyChildComponent: Replace this with your actual child component.
childPropsArray: An array where each element contains the props for a corresponding MyChildComponent.
keyPrefix: A unique string to prefix keys, ensuring they remain unique across renders.
breakpoints: Defines that for screen widths below md (768px), there will be 1 child per row; between md and xl (1280px), 2 children per row; and above xl, 3 children per row.
Additional Considerations
Flexibility: The component is generic and can handle any child component type as long as the corresponding props are provided in propsArray.
Performance: If you have a large number of breakpoints or child components, consider optimizing the component further, possibly by memoizing rows or breakpoint calculations.
Accessibility: Ensure that invisible components do not interfere with screen readers or keyboard navigation. The invisible class in TailwindCSS sets visibility: hidden;, which hides the element visually but still keeps it in the accessibility tree. If this is a concern, consider using aria-hidden="true" on invisible components or alternative methods to manage layout.
Conclusion
The ResponsiveContainer component provides a robust and flexible way to manage responsive layouts with dynamic child component rendering. By leveraging TailwindCSS and React hooks, it ensures that your UI remains consistent and adapts seamlessly to different screen sizes.