web-kabar-harapan/components/landing-page/banner-news.tsx

91 lines
2.7 KiB
TypeScript

"use client";
import { getListArticle } from "@/service/article";
import { useEffect, useState } from "react";
type Article = {
id: number;
title: string;
description: string;
categoryName: string;
createdAt: string;
createdByName: string;
thumbnailUrl: string;
categories: { title: string }[];
files: { fileUrl: string; file_alt: string }[];
};
export default function BannerNews() {
const [articles, setArticles] = useState<Article[]>([]);
const [showData, setShowData] = useState("5");
useEffect(() => {
fetchArticles();
}, []);
async function fetchArticles() {
try {
const req = {
limit: showData,
page: 1,
search: "",
categorySlug: "",
sort: "desc",
isPublish: true,
sortBy: "created_at",
};
const res = await getListArticle(req);
setArticles(res?.data?.data || []);
} catch (error) {
console.error("Gagal memuat artikel:", error);
}
}
if (articles.length === 0) return null;
const mainArticle = articles[0];
const sideArticles = articles.slice(1, 4);
return (
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4 p-4">
{/* Artikel utama */}
<div className="lg:col-span-2 relative">
<img
src={mainArticle.thumbnailUrl || mainArticle.files?.[0]?.fileUrl}
alt={mainArticle.files?.[0]?.file_alt || mainArticle.title}
className="w-full h-[400px] object-cover rounded-lg"
/>
<div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-6 rounded-b-lg">
<span className="bg-yellow-500 text-white text-xs px-2 py-1 rounded">
{mainArticle.categoryName || "Berita Terkini"}
</span>
<h2 className="mt-2 text-white text-2xl font-bold">
{mainArticle.title}
</h2>
</div>
</div>
{/* Artikel samping */}
<div className="grid grid-cols-1 gap-4">
{sideArticles.map((article) => (
<div key={article.id} className="relative">
<img
src={article.thumbnailUrl || article.files?.[0]?.fileUrl}
alt={article.files?.[0]?.file_alt || article.title}
className="w-full h-[125px] object-cover rounded-lg"
/>
<div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-4 rounded-b-lg">
<span className="bg-yellow-500 text-white text-xs px-2 py-1 rounded">
{article.categoryName || "Berita Terkini"}
</span>
<h3 className="mt-1 text-white text-sm font-semibold">
{article.title}
</h3>
</div>
</div>
))}
</div>
</div>
);
}