Next.js Discord

Discord Forum

How to Image skeleton without using useRef

Unanswered
useless posted this in #help-forum
Open in Discord
Avatar
uselessOP
i have alot of images in me landing page and i am not using a map to load them, each one has its own style, width, height, ...

how can i add skeleton loading for them without using useRef and shipping more JS to the user?



  const checkImg = () => {
    if (ImgRef.current?.complete) {
      setIsLoading(false)
    } else {
      setTimeout(() => {
        checkImg()
      }, 200)
    }
  }

 useEffect(() => {
    checkImg()
  }, [])

   return<>
       {isLoading && <Skeleton className={`h-[75vh] w-2/3`} />}

        <img
          ref={ImgRef}
          src={``}
          alt={''}
          aria-label=""
          loading="lazy"
          className={isLoading ? 'hidden' : 'rounded-3xl border'}
        />
      <>

8 Replies

Avatar
fuma πŸ’™ joulev
What should your skeleton looks like? If it's a solid color, just use the placeholder property with base64 image
You can also use [blur placeholder](https://nextjs.org/docs/pages/api-reference/components/image#blurdataurl)

Otherwise, you have to listen to the onLoad event. And display your skeleton when it's not loaded
const [isLoaded, setIsLoaded] = useState(false)
return <>
  {!isLoaded && <LoadingState />}
  <Image
     onLoad={() => setIsLoaded(true)}
     {...props}
  />
</>
Avatar
uselessOP
my skeleton is shadcn ui loading
Avatar
fuma πŸ’™ joulev
Then the above solution should works for you
Avatar
uselessOP
but i don't want to use nextjs Image
i want to use the normal img
Avatar
fuma πŸ’™ joulev
Why? Next.js Image can optimise the image for you.
And just replace Image with img, if you wanna use the native image element
onLoad event also exists in img
Avatar
uselessOP
the thing is when i deploy to netlify, Image uses lamda functions and i am limited to 125K free (i can pass that number easily in my website because of the users)