Created
March 17, 2017 17:24
-
-
Save drKnoxy/6f214e312b7f16f26374fa99738e899c to your computer and use it in GitHub Desktop.
Unsplash image grid
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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