Skip to content

Instantly share code, notes, and snippets.

@drKnoxy
Created March 17, 2017 17:24
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 drKnoxy/6f214e312b7f16f26374fa99738e899c to your computer and use it in GitHub Desktop.
Save drKnoxy/6f214e312b7f16f26374fa99738e899c to your computer and use it in GitHub Desktop.
Unsplash image grid
function ImageGrid({ images = [], imageSelect = () => {} }) {
function Img({ id = '', urls = {}, onClick = () => {}, style = {} }) {
return (
<a style={style} onClick={e => onClick(urls)}>
<img src={urls.small} alt="" />
</a>
);
}
return (
<div className="grid grid--gutters" style={{ marginTop: 8 }}>
{chunk(images).map((imgChunk, colIndex) => (
<div className="grid__col-auto" key={`col-${colIndex}`}>
{imgChunk.map(img => (
<Img
key={img.id}
{...img}
onClick={imageSelect}
style={{ marginBottom: 8 }}
/>
))}
</div>
))}
</div>
);
}
function chunk(collection = [], chunkCount = 3) {
const chunks = new Array(chunkCount).fill().map(() => []);
const heights = new Array(chunkCount).fill(0);
collection.forEach(img => {
const i = indexOfSmallest(heights);
chunks[i].push(img);
heights[i] += img.height / img.width;
});
return chunks;
function indexOfSmallest(arr) {
if (arr.length === 0) return -1;
let min = arr[0];
let minI = 0;
arr.forEach((v, i) => {
if (v < min) {
minI = i;
min = v;
}
});
return minI;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment