Categories
React Projects

Create an Image Modal with React and JavaScript

Spread the love

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create an image modal with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app image-modal

with NPM to create our React project.

Create the Image Modal App

To create the image modal app, we write:

import { useState, useEffect } from "react";

const images = [
  "https://images.dog.ceo/breeds/pomeranian/n02112018_5091.jpg",
  "https://images.dog.ceo/breeds/mountain-swiss/n02107574_753.jpg",
  "https://images.dog.ceo/breeds/leonberg/n02111129_3028.jpg"
];

export default function App() {
  const [index, setIndex] = useState(0);
  const [displayModal, setDisplayModal] = useState(false);
  const next = () => {
    setIndex((i) => (i + 1) % images.length);
  };
  const prev = () => {
    setIndex(
      (i) => (((i - 1) % images.length) + images.length) % images.length
    );
  };
  const onClickOutside = (e) => {
    if (e.target.localName !== "button") {
      setDisplayModal(false);
    }
  };

  useEffect(() => {
    window.addEventListener("click", onClickOutside);
    return () => window.removeEventListener("click", onClickOutside);
  }, []);

  return (
    <div className="App">
      <button onClick={() => setDisplayModal(true)}>open modal</button>
      {displayModal && (
        <div
          style={{
            position: "absolute",
            top: 20,
            left: 20,
            border: "1px solid gray",
            backgroundColor: "white"
          }}
        >
          <button onClick={prev}>&lt;</button>
          <img src={images[index]} alt="" style={{ width: 200, height: 200 }} />
          <button onClick={next}>&gt;</button>
        </div>
      )}
    </div>
  );
}

We have the images array with URLs of images.

The index state is created with the useState hook to let us get an images entry by its index.

The displayModal state lets us control whether to display the modal or not.

The next and prev methods cycles through the images indexes to rotate the images.

We pass in a callback to the setIndex function to return the latest value based on the current value of index , which is stored in the i parameter.

onClickOutside checks if we clicked on a button.

If we didn’t, then we call setDisplayModal to false to close the modal.

The useEffect callback adds the onClickOutside to listen to the click event of the window .

It returns a callback to let us remove the click listener with removeEventListener when we unmount it.

The empty array in the 2nd argument lets us run the useEffect callback only when we mount the App component.

In the return statement, we have a button that sets the displayModal to true when we click it.

Below that, we have the modal which is displayed with displayModal is true .

We set the modal div’s position property to absolute so that we can display it above other content.

top and left sets the position.

border adds a border.

And backgroundColor sets the background color.

Inside it, we have buttons that call prev and next when we click on them to cycle through the images.

And the img element displays the image.

Conclusion

We can add an image modal with React and JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *