Next.js Discord

Discord Forum

Trying to render preloaded images

Answered
Polar bear posted this in #help-forum
Open in Discord
Polar bearOP
basically I'm trying to make one of those apple scroll image animations: [example](https://css-tricks.com/lets-make-one-of-those-fancy-scrolling-animations-used-on-apple-product-pages/)
I can see on my network dev tools that the images are preloaded but I'm not sure how to render them with my jsx

this is how i'm preloading them
  useEffect(()=>{
    const preloadImages = () => {
      const emptyArray = [...Array(frameCount+1).keys()]
      emptyArray.forEach((element)=>{
        const img = new Image();
        img.src = `/image-sequence/animation (${element}).png`;
      })
    }
    preloadImages();
  },[])



and this is how i'm rendering them
<img
  src={`/image-sequence/animation (${frame}).png`}
  alt='sososowhat'
  className='h-auto max-w-6xl w-full'
/>

when i look at my network tag it fetches the required photo again rather than making use of the preloaded photo

any idea how to fix this?
Answered by fuma
The native Image API can’t be directly used in React.js, as an alternative, you can consider the approach mentioned by joulev. Fetch the image and convert it to base64 format. Base64 images are always supported by the image element
View full answer

6 Replies

The native Image API can’t be directly used in React.js, as an alternative, you can consider the approach mentioned by joulev. Fetch the image and convert it to base64 format. Base64 images are always supported by the image element
Answer
Polar bearOP
are these base 64 images 'preloaded'? if i make an array of them i won't need to fetch each photo and could swap them out one by one without having to fetch them each time?
Yes, you can store these images in an array, with Promise.all to fetch all images at once.
Polar bearOP
alright, i'll give it a shot, thanks
Polar bearOP
hey i just wanted to let you know it worked, thanks for your time again
Nice :meow_party: