@nouraldeen/use-img
v0.0.4
Published
A react custom hook for image loading.
Downloads
17
Maintainers
Readme
useImg React Hook
Description
useImg is a react hook that allows you to load images with a loading state and error state, and also allows you to render the image safely when it is loaded and decoded.
Installation
npm install @nouraldeen/use-img
Usage
Simplest usage:
import React from "react";
import useImg from "@nouraldeen/use-img";
const ImageWrapper = () => {
const { status, image, error } = useImg("https://example.com/image.jpg");
if (status === "loading") {
return <p>Loading...</p>;
}
if (status === "error") {
return <p>Error: {error.message}</p>;
}
if (status === "loaded") {
return <img src="placeholder.png" alt="image" />;
}
return <img src={image.src} alt="image" />;
};
export default ImageWrapper;
API
useImg(src: string): { status: 'loading' | 'error' | 'loaded' | "ready", image: HTMLImageElement | null, error: Error | null }
Explanation
by using status.ready you can know when the image is loaded and decoded and ready to be rendered safely without any flickering.
example:
status.ready && <img src={image.src} alt="image" />;
other status values are:
- status.loading: when the image is still loading.
- status.error: when the image failed to load.
- status.loaded: when the image is loaded but not decoded yet.
License
This project is licensed under the MIT License.