<ImageGallery />

Display bunch of images in a gallery fashion.

Component

1import React, { useState } from "react";
2import "./Styles/_imagegallery.scss";
3
4export default function ImageGallery({ ...props }) {
5 const { children } = props;
6
7 const firstChild = children[0].props;
8
9 const [img, setImg] = useState({ src: firstChild.src, alt: firstChild.alt });
10
11 const onImageChange = (props) => {
12 const { src, alt } = props;
13 setImg({ ...img, src, alt });
14 };
15
16 const childrenWithProps = React.Children.map(children, (child) => {
17 if (React.isValidElement(child)) {
18 return React.cloneElement(child, { onImageChange, img });
19 }
20 return child;
21 });
22
23 return (
24 <div className="Image-Gallery">
25 <div>
26 <img src={img.src} alt={img.alt} />
27 </div>
28 <div>{childrenWithProps}</div>
29 </div>
30 );
31}
32
33export { ImageGalleryItem } from "./Components/ImageGalleryItem";

Styles

1.Image-Gallery {
2 max-width: 760px;
3 margin: auto;
4 padding: 10px;
5 background: white;
6
7 & > div:first-child,
8 div:nth-child(2) {
9 width: 100%;
10 }
11
12 & > div:nth-child(2) {
13 display: grid;
14 grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
15 padding-top: 10px;
16 grid-gap: 0.5px 10px;
17 grid-auto-rows: 10px;
18
19 & > img {
20 cursor: pointer;
21
22 &.is-active {
23 opacity: 0.5;
24 }
25 }
26 }
27}
28
29// grid-template-columns: repeat(4, 1fr);
30// grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));

Usage

1