кастомный хук.
js
const AdaptiveImage = ({
src,
width,
height,
alt,
...rest
}) => {
const { isIE, isSafari } = useDeviceDetect();
const isSupportWebp = !(isIE || isSafari);
const { width: screenWidth, isMobile, isTablet } = useAdaptive();
const quality = (isMobile && QUALITY_FOR_MOBILE) || (isTablet && QUALITY_FOR_TABLET) || DEFAULT_QUALITY;
const mobilePixelRatio = 2;
const realScreenWidth = (isMobile || isTablet) ? screenWidth * mobilePixelRatio : screenWidth;
// расчет размера картинки
const deviceSizes = [300, 400, 500, 600, 700, 800, 900, 1150];
const ratio = width / height;
const adaptiveWidth = (deviceSizes.reduce((prev, curr) => (Math.abs(curr - realScreenWidth) < Math.abs(prev - realScreenWidth) ? curr : prev)));
const adaptiveHeight = (adaptiveWidth / ratio).toFixed(0);
return (
<img
src={loaderImage(src, adaptiveWidth, adaptiveHeight, isSupportWebp, quality)}
alt={alt}
width={adaptiveWidth}
height={adaptiveHeight}
{...rest}
/>
);
};
export default AdaptiveImage;
Должно получиться такое:
js
const AdaptiveImage = ({
src,
width,
height,
alt,
...rest
}) => {
const {imageSrc, adaptiveWidth, adaptiveHeight, isSupportWebp, quality} = useAdaptiveImage(src, width, height)
return (
<img
src={loaderImage(imageSrc, adaptiveWidth, adaptiveHeight, isSupportWebp, quality)}
alt={alt}
width={adaptiveWidth}
height={adaptiveHeight}
{...rest}
/>
);
};
export default AdaptiveImage;
Обсуждают сегодня