reactjsimage-gallery

React Site wont render as soon as button is added around <img/>


I am trying to make a dynamic and good looking picture gallery but i am having a problem. Since i want the images to be clickable (so i can expand them) i need to wrap a button around the images. For some reason this is crashing react. I tried around 5 different ways of implementing the button. Sadly none worked

My Code currently looks like this:

import { useState, useEffect } from 'react';
import "./styles/gallery.css"
import Masonry, {ResponsiveMasonry} from 'react-responsive-masonry';
function Gallery() {
  const [pictures, setPictures] = useState([]);
  const [popup, togglepopup] = useState(false);

  useEffect(() => {
    const importPictures = async () => {
      const context = require.context('../pictures/gallery', false, /\.(png|jpe?g|svg)$/);
      const files = context.keys();
      const pictures = await Promise.all(files.map(async (file) => {
        const image = await import(`../pictures/gallery/${file.slice(2)}`);
        return {
          src: image.default,
          alt: file.slice(2, -4),
        };
      }));
      setPictures(pictures);
    };
    importPictures();
  }, []);

  return (
    <div className="galleryElements">
    <ResponsiveMasonry columnsCountBreakPoints={{300: 1, 750: 2, 900: 3, 1400: 4, 1900: 5, 2100: 6}}>
      <Masonry gutter='1rem'>
      
      {pictures.map((picture) => (
        <button className='elementButton' type="button" onClick={togglepopup(!popup)}>
        <img className="element" src={picture.src} alt={picture.alt} key={picture.alt} />
        </button>
      ))}
      
      </Masonry>
    </ResponsiveMasonry>
    
    </div>
    
  );
}

export default Gallery;

If i remove the button everything works and is rendered correctly. If it is in there only the background color is rendered. Nothing else. No Navbar, no Footer etc. If you know any other way of making the popout feature possible i would be glad to hear it.


Solution

  • You can use onClick in your <img/> you don't really need <button> to do that :

    <img 
     className="element"
     src={picture.src} 
     alt={picture.alt} 
     key={picture.alt}
     onClick={() => {
       togglepopup(!popup)
     }}
     />