Macjeje
Macjeje

Reputation: 37

Rendering different images in a modal based on what button is clicked

I would like to change the content inside a modal based on what button is clicked on.

Depending on the button clicked, a different array of images will be provided to render new <img> tags in the modal.

From my understanding the useState hook should be used here along with map to render each image from the provided image array.

Below is a simplified version of my current code.

const ModalGallery = () => {
  ...
  const [ modalContent, setModalContent ] = useState([]);
  const loadImages = imageArray => {
    // code that uses map and setModalContent ?
  };

  return (
    <>
      {projects.map(project => {
        return (
          <Button
            onClick={() => {
              // call a funtion that changes the images rendered in the modal
              loadImages(project.images);
            }}
          >
            Display
          </Button>
        );
      })}
      <Modal>
        {modalContent}
      </Modal>
    </>
  );
};

export default ModalGallery;

Upvotes: 0

Views: 167

Answers (1)

dileep nandanam
dileep nandanam

Reputation: 2895

You should maintain image urls in modalContent, then on click, change modalContent with image url's of corresponding project, which cause the Modal element to get updated.

const ModalGallery = () => {
  ...
  const [modalContent, setModalContent] = useState([]);
  const [showModal, setShowModal] = useState(false)

  const modal = () => {
    return(
      <Model>
        {
          modalContent.map((img_url) =>{
            return(<img src={img_url} key={img_url} />)
          })
        }
      </Model>
    )
  }

  return (
    <>
      {projects.map(project => {
        return (
          <Button
            onClick={() => {
              // call a funtion that changes the images rendered in the modal
              setModalContent(project.images);
              setShowModal(true)
            }}
          >
            Display
          </Button>
        );
      })}
      {showModal ? modal : null}
    </>
  );
};

Upvotes: 2

Related Questions