Open In App

How To Add Images From API To Tailwind Card in React?

Last Updated : 16 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Displaying images fetched from an API in a Tailwind-styled card in React involves data fetching, state management, and styling. In this article, we will see how we can add images from an API to a Tailwind Card in React.

Approach

The approach involves the following steps:

  1. Setup React Project: Create a React app using Vite and set up Tailwind CSS for styling.
  2. Create a Card Component: Build a reusable card component using Tailwind CSS.
  3. Fetch Data from API: Use Axios or Fetch API to get image data from a source like Unsplash.
  4. Display Images: Map over the fetched data and render the images inside the Tailwind card component.

This structured approach ensures the app is modular, easy to maintain, and scalable for adding more features later.

Steps To Add Images from API to Tailwind Card in React

Step 1: Set Up a React Application

Create a new React project using Vite:

npx create-vite@latest my-react-app --template react
cd my-react-app
npm install

Step 2: Install Tailwind CSS

Install Tailwind CSS and set it up:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

Configure Tailwind in tailwind.config.js:

// tailwind.config.js

module.exports = {
content: ["./src/**/*.{js,jsx,ts,tsx}"],
theme: {
extend: {},
},
plugins: [],
};

Add Tailwind’s CSS to src/index.css:

/* src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

Folder Structure

gh
Folder Structure

Dependencies

"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.1",
"autoprefixer": "^10.4.20",
"eslint": "^9.9.0",
"eslint-plugin-react": "^7.35.0",
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
"eslint-plugin-react-refresh": "^0.4.9",
"globals": "^15.9.0",
"postcss": "^8.4.45",
"tailwindcss": "^3.4.11",
"vite": "^5.4.1"
}

Step 3: Create the Card Component

Create a card component to display the images.

JavaScript
// src/Card.js


const Card = ({ image, title }) => {
    return (
        <div className="max-w-sm rounded overflow-hidden shadow-lg bg-white">
            <img className="w-full" src={image} alt={title} />
            <div className="px-6 py-4">
                <div className="font-bold text-xl mb-2">{title}</div>
            </div>
        </div>
    );
};

export default Card;

Step 4: Fetch Images from an API

Fetch images from an API and display them using the ImageCard component.

JavaScript
// src/App.js

import React, { useEffect, useState } from "react";
import Card from "./Card";

const App = () => {
    const [images, setImages] = useState([]);

    useEffect(() => {
        const fetchImages = async () => {
            try {
                const response = await fetch(
                    "https://api.unsplash.com/photos/?client_id=Your API Key"
                );
                const data = await response.json();
                setImages(data);
            } catch (error) {
                console.error("Error fetching images:", error);
            }
        };

        fetchImages();
    }, []);

    return (
        <div className="container mx-auto p-4 grid grid-cols-1
        sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
            {images.map((image) => (
                <Card
                    key={image.id}
                    image={image.urls.small}
                    title={image.alt_description || "Untitled"}
                />
            ))}
        </div>
    );
};

export default App;


To start the application run the following command.

npm run dev

Output

fefe
Add Images from an API to a Tailwind Card in React

Next Article

Similar Reads