"use client";
import React, { useState, useEffect, useRef } from "react";
import Link from "next/link";
export default function BlogList({ blogs }) {
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 12;
const listRef = useRef(null);
const totalPages = Math.ceil(blogs.length / itemsPerPage);
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = blogs.slice(indexOfFirstItem, indexOfLastItem);
// Scroll to top of the list when page changes
useEffect(() => {
if (listRef.current) {
// Scroll to the top of the blog section, adjusting for some offset if needed
const yOffset = -100; // Adjust for header height if sticky
const y = listRef.current.getBoundingClientRect().top + window.pageYOffset + yOffset;
window.scrollTo({ top: y, behavior: 'smooth' });
}
}, [currentPage]);
const paginate = (pageNumber) => setCurrentPage(pageNumber);
const nextPage = () => currentPage < totalPages && setCurrentPage(currentPage + 1);
const prevPage = () => currentPage > 1 && setCurrentPage(currentPage - 1);
return (
<>
{currentItems.map((blog, i) => (
{blog.title.length > 35
? blog.title.slice(0, 35) + "..."
: blog.title}
{blog.shortDesc.length > 80
? blog.shortDesc.slice(0, 80) + "..."
: blog.shortDesc}
Read More
))}
{/* Pagination Controls */}
{totalPages > 1 && (
{/* Previous Button */}
-
{/* Page Numbers */}
{Array.from({ length: totalPages }, (_, i) => i + 1).map((number) => (
-
))}
{/* Next Button */}
-
)}
>
);
}