Search code examples
reactjsloader

How to set a loader or skeletor for every single card item?


I want to set skeletor for my every single blog item. How can i write this code. My Code Was.

<div className="grid sm:grid-cols-3 gap-[3rem]">
          {blogs.map((blog,index)=>{
            return(
              <>
                {loading ? (<Skeleton/>) : (
                  <BlogCard
                    key={index}
                    id={blog.id}
                    title={blog.title}
                    thumbnail={blog.thumbnail}
                    description={blog.description}
                    tag={blog.tag}
                    category={blog.category}
                    created_at={blog.created_at}
                />
                )}
              </>
            )})}
        </div>

But its not working as I want.

Kindly help me please.


Solution

  • blogs will have no elements when loading, so <Skeleton/> wont show

    put a seperate placeholders with expected no of blogs

    const expectedBlogs = 7;
    // can chance this to show the loader for previous no of blogs/per page items
    const placeholderBlogs = Array.from({ length: expectedBlogs }, (_, i) => i);
    
    
      <div className="grid sm:grid-cols-3 gap-[3rem]">
             { // when loading show the Skeleton for each blog
              loading ? 
                placeholderBlogs.map((_, idx) => (<Skeleton key={idx} />)) 
               : (
                 blogs.map((blog,index) => {
                   return(
                      <BlogCard
                        key={index}
                        id={blog.id}
                        title={blog.title}
                        thumbnail={blog.thumbnail}
                        description={blog.description}
                        tag={blog.tag}
                        category={blog.category}
                        created_at={blog.created_at}
                    />
                )})
               )
             }    
            </div>
    

    Hope it helps