joelmturner pyramid logo

About

Blog

Illustration

TIL

Uses

About

Blog

Illustration

TIL

Uses

Build a React Gallery With CSS Grid

Table of Contents

TypeScript

Now, let's type it. This will help us and others know what we shape we need passed to the gallery.

import React from 'react';
import Img, { FluidObject } from 'gatsby-image';
type GallerySizes = 's' | 'm' | 'l';
type GalleryImage = {
node: {
localImage: {
childImageSharp: {
fluid: FluidObject;
};
};
id: string;
};
};
type GalleryProps = {
imageNodes: GalleryImage[];
size?: GallerySizes;
};
function Gallery({ images, size = 'm' }: GalleryProps) {
function getStylesForSize(): React.CSSProperties {
switch (size) {
case 's':
return {
gridTemplateColumns: 'repeat(auto-fill, minmax(142px, 1fr))',
gridGap: '0.25rem',
};
case 'm':
default:
return {
gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',
gridGap: '0.5rem',
};
case 'l':
return {
gridTemplateColumns: '1fr',
gridGap: '.75rem',
};
}
}
const wrapperStyles: React.CSSProperties = {
display: 'grid',
...getStylesForSize(),
};
return (
<div style={wrapperStyles}>
{nodes.length > 0 &&
nodes.map((node) => <Img fluid={node.localImage.childImageSharp.fluid} />)}
</div>
);
}

Nice! Now we have a functioning gallery component that can change sizes. You can see my implementation of this on the illustration page.


Discuss this article on Twitter

Category:

dev

© 2012-2023, built with Next.js and Chakra UI

InstagramtwitterlinkedIngithubjoelmturner's DEV Profilejoelmturner's Mastodon Profile