When providing high quality images to users especially the ones with slower internet, it's important to tell them that images are being loaded. So I'm gonna share how to display blurry images while loading the actual images on React app withou any plugins / libraries just like I did in my portfolio.
Setup
You have to make a small version of your images (about 50px) and encode them here (you can put the entire folder and decode them all together). After it's encoded, click on "copy image".This step is annoying but everything else is very simple.
Import
...waiting for Gist...
I like to keep the attributes consistent so that you can treat the component the same way you would treat an "img" tag. Additionally, you have to define "src64" which the code you copied earlier should go.Provide the blurry image
Now let's actually get into blurry loading images....waiting for Gist...
Reason I'm not doing "{...props}" is that "src" attribute changes.The original image will only load when the state "loaded" is true. While it's false it displays the Base64 image. When this FC(functional component) is called, useEffect calls "loadImage" function which I will go over next. As soon as "loadImage" is over, "loaded" becomes true.
Wait for the image to Load
Finally, the "loadImage" function....waiting for Gist...
Basically what it does is when the specified image finishes loading it tells your FC about it.Dynamic Image Loading
Above was everything you need to know. However, let's make it to the next level.You might want to re-use the same "img" tag to display different images or load the image in the specific timing (ie. slidshow, scrolling) just like shown below.
...waiting for Gist...
This is when "useEffect" comes in very handy....waiting for Gist...
This way, everytime "src" changes it's gonna repeat the same method and it's only when "load" is true.Should you do this?
This method is definitely a good option when you want to have control over the image loading method and how the loading images to look like (you can even switch to completely something else).However, encoding images can be very time consuming and is one of the reasons that you should consider using frameworks and plugins. Gatsby is one of the great options. In fact, I use it for this blog lol
In addition to that, you don't have that beautiful smooth transition with this method and sometimes it's flickery when switching to the actual image. React-spring can probably help you with that.