Skip to content

Instantly share code, notes, and snippets.

@andrisgauracs
Last active December 30, 2018 22:01
Show Gist options
  • Select an option

  • Save andrisgauracs/4fc7aea7131e233d17dfa429886ba070 to your computer and use it in GitHub Desktop.

Select an option

Save andrisgauracs/4fc7aea7131e233d17dfa429886ba070 to your computer and use it in GitHub Desktop.
A new img component, that will act just like the basic img tag, but in addition will provided an asynchronous image preload
/* We utilize the createResource provied by React,
which allows to access the image data asynchronously */
const ImageResource = unstable_createResource(
source =>
new Promise(resolve => {
const img = new Image();
img.src = source;
img.onload = resolve;
})
);
/* We create a new img component, that will read and display
the full resolution picture from the cache, once it gets loaded */
const Img = ({ src, alt, ...props }) => {
ImageResource.read(src);
return <img src={src} alt={alt} {...props} />
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment