React component to create a thumbnail of an exisiting <img/> element without creating a new
<img/> with the same src. It’s useful if the image is a non-cached/dynamic resource and the
thumbnail is created asynchronously. If we use another <img/> with the same src but smaller
size then it will trigger another request to the server for the same resouce.
The following example shows how to use the component with default options:
import Thumbnail from '@react-packages/image-thumbnail';
...
const imgRef = React.useRef<HTMLImageElement>(null);
...
<img id="imageId" ref={imgRef} ... />
...
<Thumbnail image={imgRef.current /*or `document.getElementById("imageId")`*/} ... />
imageimg element that the thumbnail will reflect the image from it.classNameestyle To change some options, we must use createComponent function as the following example:
import {createComponent} from '@react-packages/image-thumbnail';
const Thumbnail = createComponent({
...
});
...
<Thumbnail image={imgRef.current /*or `document.getElementById("imageId")`*/} ... />
createComponent function takes one parameter whose type of object. The object is defined as
follows:
type Params = {
noImage?: React.ReactNode,
ratioX?: number,
ratioY?: number,
styles?: {
background?: TStyle,
content?: TStyle,
},
};
where TStyle is
{
className?: string,
style?: CSSProperties,
}
noImage
It will be rendered when image prop is null or the thumbnail image is failed
to create.
Default value: an svg element which depicts an “no image” icon.
ratioX
Along with ratioY, it determines the ratio between width and height of the
thumbnail area.
Default value: 1
ratioY
Along with ratioX, it determines the ratio between height and width of the
thumbnail area.
Default value: 1
styles
It defines CSS styles for the elements rendered by the thumnail component. It will be clear if we
show the structure of elements rendered by the thumbnail component and how styles is applied.
The following code is the elements:
<div
className={props.className}
style={props.style}
>
<Rect
{...styles.background}
ratioX={ratioX}
ratioY={ratioY}
>
{props.image ? (
<div {...styles.content}>
<canvas ... /> {/* This `canvas` element displays the thumbnail image */}
</div>
) : noImage}
</Rect>
</div>