React lazy image loading and TypeScript — No more slow and broken images
Creating a better UX is not as simple as it looks. Every component on-page matters. While working on a complex piece of code, we almost forgot about the simplest thing, a broken image.
Here in this tutorial, I will explain how you can create a simple Image
component without breaking existing code. This component will support lazy loading and broken images.
1. Create an Image Component
To start with, first create a folder in your component library and create a file named index.tsx
.
mkdir -p components/Image
touch components/Image/index.tsx
Add below line to index.tsx
.
// components/Image/index.tsx
import React from "react";interface ImageProps extends React.ImgHTMLAttributes<HTMLImageElement> {}export default ({ ...props }: ImageProps) => {
return <img {...props} />;
};
Note: I am using typescript to build this component. You can just remove typing if your project does not support typescript.
2. How to consume in App Page
You can consume the Image component just like img HTML element. Since this image component extends HTMLImageElement.
It supports all the Image properties.
// App.tsximport React from "react";
import Image from "./components/Image";function App() {
return (
<div className="App">
<section className="section">
<div className="container">
<h1 className="title">React Components Demo</h1>
<p className="subtitle">Lazy Image</p>
<Image
style={{ width: 400, height: 300 }}
src="https://upload.wikimedia.org/wikipedia/commons/f/ff/Pizigani_1367_Chart_10MB.jpg"
/>
<br />
<Image src="https://doesnot.exits.com/image.png" />
</div>
</section>
</div>
);
}export default App;
Try to reload the page, you will notice the image load very slowly. This is because the image is 10mb
large. Same time the other image will be broken.