I'm building an image gallery inside an Astro website with a list of menu items that, after click, change the state and then trigger a rerender. I built a working prototype using React:
This is SubMenuSelectedWork.jsx
import React, { useEffect, useState } from 'react';
export function SubMenuSelectedWork ({items}) {
const [activeMedium, setcurrentMedium] = useState("weavings");
function handleClick(e) {
const className = e.target.className;
setcurrentMedium(className);
}
const filteredUrls = items.filter((item) => item.includes(activeMedium));
console.log(filteredUrls);
useEffect(() => {
console.log(activeMedium);
})
return (
<>
<nav className="selected-work-submenu" id="selected-work">
<ul>
<li onClick={handleClick} className='weavings'>Weavings</li>
<li onClick={handleClick} className='sculpture'>Sculpture</li>
<li onClick={handleClick} className='drawings'>Drawings</li>
<li onClick={handleClick} className='performance'>Performance Art</li>
</ul>
</nav>
<div style={{display: 'grid' }}>
{filteredUrls.map((item, index) => <img style={{height: '300px'}} src={item} key={index}></img>)}
</div>
</>
);
};
export default SubMenuSelectedWork;
Here's the Astro component SubGallery.astro:
---
import SubMenuSelectedWork from "./SubMenuSelectedWork";
import type { ImageMetadata } from 'astro';
const images = import.meta.glob<{ default: ImageMetadata }>('/src/assets/**/*.{jpeg,jpg,JPG,png,gif}', {eager: true, query: "?url", import: 'default'});
const imageUrls = Object.keys(images);
<SubMenuSelectedWork items={imageUrls} client:load></SubMenuSelectedWork>
The issue is that I'd like to use the Astro Image component for it's optimizing properties etc. But I can't figure how I could do that and retain the same functionality here. There's another Stack Overflow question that seems to point me in the right direction: Astro JS / Javascript : Replace image with image clicked but I'm unsure if this would work with this logic/functionality.
Is my best bet to use active class on elements that make them visible and get rid of State altogether? Or is there a better way of handling this? Thank you!