Creating react image gallery using tailwind and vite js
React image gallery is a fantastic project to enhance your react skills. Showcase it in your portfolio and increases your impression. Today, I am going to teach you how to create it. I assume that you are familiar with react hooks and fetch API. React hooks makes it easy to code this project.
This project is wholly coded in react. To understand this project basic knowledge of react js is required. I also provided the source code of this project for you. You can directly copy the code and try it out.
About react image gallery
This is an entirely dynamic image gallery using react js and tailwind. It contains animation to make it user-friendly. With a beautiful layout like the Pinterest website. Images are fetched in this gallery using API. This API is from the “Lorem Picsum”. Every image performs an effect on hovering. This gallery comes with a great feature as when you click any image, it will display in a fullscreen popup. This popup comes with a close icon. Try to demo and explore it on your own.
Prerequisites
To understand this project, You should be familiar with react and some ES6 topics such as the fat arrow function, ternary operator, async…await, error handling, fetch API, react hooks, etc. JavaScript is the base of react js so, it is important to learn it before starting this project. This project uses the tailwind for styling. So, check out tailwind first. Use standard CSS if you don’t want to go with the tailwind. This project does not require much knowledge. If you have a basic understanding of react js and tailwindcss, you are ready to start.
Add Ons
Setting up the environment
Now create a folder inside your current folder named “components”.
Then add a file inside the “components” folder named “Image.jsx”.
Adding code to App.jsx file
Now add the react source code given below and paste it into the “App.jsx” file.
import React, { useEffect, useState } from 'react'
import Image from './components/Image'
const App = () => {
const [Data, setData] = useState("")
const getData = async () => {
try {
const api = await fetch("https://picsum.photos/v2/list")
// const data = await api.json()
setData(await api.json())
} catch (error) {
console.log(error);
}
}
useEffect(() => {
getData()
}, [])
return (
// main container
<div className='w-full h-full bg-slate-900 flex justify-center py-2 overflow-hidden
relative'>
{/* Gallery container */}
<div className="rounded sm:columns-2 md:columns-3 xl:columns-4 gap-2 w-11/12 box-border">
{/* Rendering Image component for every image url in our api*/}
{Data ? (Data.map((item, index) => { return (<Image url={item} key={item.id} />) })) : "NoT images found"}
</div>
</div>
)
}
export default App
Understanding the source code
In react, everything is a component. Here App components return some JSX. JSX is almost similar to HTML.
In JSX, the main container is created and styled by tailwindcss classes. The main container contains a gallery container that displays all the images. Inside the gallery, a ternary operator checks whether image data is fetched or not. If image data is fetched it runs a map function that renders the “Image” component for every image. It also passes image data as props to the image component.
A react hook named “use effect” calls an asynchronous function named “getData” on every screen reload. “getData” function uses the try…catch method to handle errors. And fetch images api. After fetching, it stores the fetched api data to the “useState” react hook in JSON format. Now “useState” method set the api data to the current data. This stores api data in the Data variable which uses in the ternary operator.
Import key at the top imports the components and resources from other files.
Now we completed the App.jsx file. It is time to code the Image component to display images and popups.
Adding code to Image.jsx file
Copy the code given below and paste it into your Image.jsx file-
import React, { useState } from 'react'
import { IoClose } from "react-icons/io5";
const Images = (props) => {
const [popup, setPopup] = useState(false)
const [popupData, setpopupData] = useState("")
// console.log(props);
return (
<>
{/* Popup box container */}
<div className={`fixed left-1/2 ${popup ? "top-1/2 opacity-100 " : "top-[-150%] opacity-0 "
} -translate-x-1/2 -translate-y-1/2 w-full h-full bg-slate-900 rounded-md flex justify-center items-center z-40 transition-all duration-300 ease-in-out`}> <IoClose
className="w-16 h-16 text-white absolute right-0 top-0 z-50"
onClick={() => {
setPopup(false);
}}
/>
{/* Image shown on popup */}
<img src={popupData} className="w-full sm:w-5/6 md:w-1/2" /></div>
{/* image which display in gallery */}
<img
src={props.url.download_url}
onClick={(e) => {
setpopupData(e.target.src)
setPopup(true)
}}
alt="gallery"
className='w-full mb-2 rounded-xl hover:scale-110 shadow-2xl hover:shadow-slate-900 transition' />
</>
)
}
export default Images
Understanding the source code
In this file, we import react-icons and other resources.
The image component contains two states-
The first state has a boolean value that determines when to show the popup. When it has a “true” value popup appears and when it has a “false” value popup disappears.
The second state contains the url of the clicked image. This url will pass into the image element inside the popup. This displays the image in large size.
JSX is the main part of this component. Let’s understand it.
Here JSX has two elements popup container and the main image tag.
The main image tag has four attributes alt, className, src, and an event listener.
In the src attribute, the image url is passed with the help of props from the App.jsx file. An event listener triggers after clicking an image and calls a function. This function passes the current image url and a “true” boolean value to the states defined above.
Now let’s move on popup container.
The Popup container contains a close icon and an image tag. In its class, a ternary operator is added which boolean value of the state. If the condition is true then, it adds some classes which make the popup visible. If the condition is visible then, it hides the classes.
This icon has some basic tailwind classes and an event listener. This event listener sets the boolean state value to “false”.
The image tag excepts the current image url from the state. And this shows the image in large size.
That’s how this code works. It is as simple as. Try it yourself.
Conclusion
At last, this reacts image gallery is a great project to develop your skills. You can mention it in your portfolio.
I am sure you learned something new from this project. If you have any queries tell us in a comment we will do our best.
Thank you!