Skip to content

Commit d37c71e

Browse files
committed
feat(ktl-2781): render grid as single column on mobile
1 parent 2b5d3a1 commit d37c71e

File tree

1 file changed

+23
-6
lines changed

1 file changed

+23
-6
lines changed

components/masonry-grid/masonry-grid.tsx

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import cn from 'classnames';
2-
import { useMemo, ReactNode } from 'react';
2+
import { useMemo, ReactNode, useEffect, useState } from 'react';
33
import styles from './masonry-grid.module.css';
44

55
export interface MasonryGridProps<T> {
@@ -11,6 +11,7 @@ export interface MasonryGridProps<T> {
1111
className?: string;
1212
columnClassName?: string;
1313
itemClassName?: string;
14+
mobileBreakpoint?: number;
1415
}
1516

1617
export function MasonryGrid<T>({
@@ -21,18 +22,34 @@ export function MasonryGrid<T>({
2122
getKey,
2223
className,
2324
columnClassName,
24-
itemClassName
25+
itemClassName,
26+
mobileBreakpoint = 808,
2527
}: MasonryGridProps<T>) {
28+
const [isMobile, setIsMobile] = useState(false);
29+
30+
useEffect(() => {
31+
const update = () => {
32+
if (typeof window !== 'undefined') {
33+
setIsMobile(window.innerWidth <= mobileBreakpoint);
34+
}
35+
};
36+
update();
37+
window.addEventListener('resize', update);
38+
return () => window.removeEventListener('resize', update);
39+
}, [mobileBreakpoint]);
40+
41+
const effectiveColumnCount = Math.max(1, isMobile ? 1 : columnCount);
42+
2643
const columns = useMemo(() => {
27-
const cols: T[][] = Array.from({ length: columnCount }, () => []);
44+
const cols: T[][] = Array.from({ length: effectiveColumnCount }, () => []);
2845

2946
items.forEach((item, index) => {
30-
const columnIndex = index % columnCount;
47+
const columnIndex = index % effectiveColumnCount;
3148
cols[columnIndex].push(item);
3249
});
3350

3451
return cols;
35-
}, [items, columnCount]);
52+
}, [items, effectiveColumnCount]);
3653

3754
const style = gap !== undefined ? { gap: `${gap}px` } : undefined;
3855

@@ -45,7 +62,7 @@ export function MasonryGrid<T>({
4562
style={style}
4663
>
4764
{column.map((item, itemIndex) => {
48-
const originalIndex = columnIndex + itemIndex * columnCount;
65+
const originalIndex = columnIndex + itemIndex * effectiveColumnCount;
4966
return (
5067
<div
5168
key={getKey(item, originalIndex)}

0 commit comments

Comments
 (0)