Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use onClink in your <img/> you dont really need <button> to do that :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading