DEV Community

Cover image for Create Cool React Image Gallery
Marianna
Marianna

Posted on

Create Cool React Image Gallery

Image gallery is one of the most important parts of any website. Today I want to show you how to create a responsive image gallery with React.

Step 1
Firstly we need some images to display in our gallery. For this we will use Lorem.space website to get random placeholder images. You can choose any category you want but I will go with shoes πŸ‘Ÿ.
We will create an array that will contain URLs of our images. For this tutorial I will use three images but of course you can have more images if you want.

const images = [
  {
    url: "https://api.lorem.space/image/shoes?w=400&h=400&hash=8B7BCDC2"
  },
  {
    url: "https://api.lorem.space/image/shoes?w=400&h=400&hash=500B67FB"
  },
  {
    url: "https://api.lorem.space/image/shoes?w=400&h=400&hash=4F32C4CF"
  }
];
Enter fullscreen mode Exit fullscreen mode

Step 2
After that we will create a functional React component for our app:

export default function App() {
  return (
    <div
      style={{
        flexDirection: "row",
        display: "flex",
        justifyContent: "center",
        alignContent: "center"
      }}
    >
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

We will use React style prop to center our div.
Step 4
In our gallery we want to have one main image and two secondary images that will have less opacity. In order to do that we need to create a component for our image:

const Image = ({ src, setMainImg, mainImg }) => {
  const [opacity, setOpacity] = useState(0.6);
  const [srcUrl, setSrcUrl] = useState(src);

  return (
    <img
      src={srcUrl}
      alt="new"
      height="250"
      width="250"
      style={{ opacity: opacity }}
      onMouseOver={() => {
        setOpacity(0.8);
      }}
      onMouseOut={() => {
        setOpacity(0.6);
      }}
      onClick={() => {
        setMainImg(srcUrl);
        setSrcUrl(mainImg);
      }}
    />
  );
};
Enter fullscreen mode Exit fullscreen mode

The Image component will receive 3 props: src - URL of the image, setMainImg - hook to manage app state and mainImg - URL of the main image. We want to change the main image on click. To do that we use onClick prop. And also we want to change the opacity of the secondary image on hover. We can do this with the use of onMouseOver and onMouseOut props.
Also in our App component we will specify the initial value of the main image URL and the state management function with the useState React hook:

const [mainImg, setMainImg] = useState(images[0].url);
Enter fullscreen mode Exit fullscreen mode

That's it! You should be able to see something like this:
React Image Gallery Demo

You can view a live demo of the image gallery on my CodeSandBox

Thank you for reading and happy coding!😊!

Top comments (0)