Skip to content

Instantly share code, notes, and snippets.

@Jiny3213
Created November 14, 2024 06:50
Nextjs images gallery page with chakra, overview your images(especially SVG) more convenient
'use client'
import { Image, useToast, Text, Flex } from "@chakra-ui/react";
import copy from 'copy-to-clipboard';
export default function ClientImage({
src,
fileName
}: {
src: string,
fileName: string
}) {
const toast = useToast()
return (
<Flex
flexDirection="column"
alignItems="center"
justify="center"
gap="16px"
w="200px"
h="200px"
cursor="pointer"
border="1px solid #fff"
onClick={() => {
copy('public' + src)
toast({
title: 'copied',
description: 'public' + src,
status: 'success',
duration: 1500,
})
}}
>
<Image
src={src}
w="100px"
h="100px"
_hover={{
bg: 'red'
}}
/>
<Text textAlign="center" fontSize="14px" color="#fff">{fileName}</Text>
</Flex>
)
}
import fs from 'fs';
import path from 'path';
import { Box, Image, Flex, Button, Center } from '@chakra-ui/react';
import ClientImage from './ClientImage';
interface GallerySearchParams {
path: string
}
export default function Gallery({
searchParams
}: {
searchParams: GallerySearchParams;
}) {
const defaultPath = '/images/icon/your-default-images-path/';
let images: string[] = [];
let dirs: string[] = [];
let dir = searchParams.path || defaultPath
const loadImages = async () => {
try {
const files = fs.readdirSync(
path.join(__dirname, `../../../../public${dir}`)
);
dirs = files.filter((file) => {
return !/\./.test(file);
});
images = files.filter((file) => {
return /\.(jpg|jpeg|png|gif|svg)$/i.test(file);
});
} catch (error) {
console.error('Failed to load images:', error);
}
};
loadImages();
return (
<Box
bg='#888'
minH='100vh'
>
<Flex p='8px'>
<Button
as='a'
href={`/gallery?path=${dir.match(/^(.*\/).*\/$/)?.[1] || defaultPath}`}
>
Back
</Button>
</Flex>
<Flex flexWrap='wrap'>
{dirs.map((item) => (
<Center
key={item}
w='200px'
h='200px'
cursor='pointer'
border='1px solid #fff'
color='#fff'
fontSize='20px'
as='a'
href={`/gallery?path=${dir}${item}/`}
>
{item}
</Center>
))}
{images.map((image, index) => (
<ClientImage
key={image}
src={`${dir}${image}`}
fileName={image}
></ClientImage>
))}
</Flex>
</Box>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment