Skip to content

Instantly share code, notes, and snippets.

@ynifamily3
Created May 28, 2022 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ynifamily3/bf52072f8d8a1f998c85191a3af7a342 to your computer and use it in GitHub Desktop.
Save ynifamily3/bf52072f8d8a1f998c85191a3af7a342 to your computer and use it in GitHub Desktop.
Masonry
import { useEffect, useMemo, useRef, useState } from "react";
function App() {
const data = Array.from({ length: 7 });
const [positions, setPositions] = useState<
Array<{ left: number; top: number }>
>([]);
const containerRef = useRef<HTMLDivElement>(null);
const heights = useRef<Array<number>>(
Array.from({ length: 10 }, () => Math.random() * 801)
);
useEffect(() => {
const heights = [...containerRef.current!.children].map(
(i) => i.clientHeight
);
console.log(heights);
const gap = 20;
const width = 300;
const cols = 3;
let _positions: Array<{ left: number; top: number }> = [];
for (let i = 0; i < heights.length; i++) {
const left = (i % cols) * (width + gap);
const top =
i < cols ? 0 : _positions[i - cols].top + heights[i - cols] + gap;
console.log(i, left, top);
_positions.push({ left, top });
}
setPositions(_positions);
}, []);
return (
<div ref={containerRef} className="relative w-[960px]">
{data.map((_, index) => (
<div
key={index}
className="absolute top-0 left-0 w-[300px] bg-slate-300"
style={{ height: heights.current[index], ...positions[index] }}
>
{index}
</div>
))}
</div>
);
}
export default App;
// 제네레이터로 구하면 되는구나 (-ㅁ- ->?)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment