react-lazy-load-image-component icon indicating copy to clipboard operation
react-lazy-load-image-component copied to clipboard

Use placeholder prop with opacity effect

Open jotamodesto opened this issue 4 years ago • 1 comments

If I'm not mistaken the blur and black and white effects are related to the placeholderSrc, and opacity creates a blank space then transition to the loaded image.

It would be nice if I define placeholder prop, then the opacity effect could use it

Ex: <LazyLoadImage src="some-big-image.jpg" placeholder={<div>Loading...</div>} effect="opacity" />

jotamodesto avatar Apr 17 '20 18:04 jotamodesto

Hi @jotamodesto I'd love to use this feature too. As seems not to be supported for now I've implemented my own version using a component like this. I hope it helps. It uses the children as placeholder, but I guess you could use any other prop.

import { useState } from "react";
import { LazyLoadImage } from "react-lazy-load-image-component";
import "react-lazy-load-image-component/src/effects/opacity.css";
import styled from "styled-components";
import logger from "../../../logger/Logger";

type ImageProps = {
    src: string;
    alt: string;
    height?: number;
    width?: number;
    visibleByDefault?: boolean;
    children?: React.ReactChild;
};

type ImageContainerProps = {
    height?: number;
    width?: number;
};

const ImageContainer = styled.div<ImageContainerProps>`
    height: ${(props) => props.height}px;
    width: ${(props) => props.width}px;
    position: relative;
`;
const LazyImage = styled(LazyLoadImage)`
    position: absolute;
    top: 0;
    left: 0;
`;

const Image = (props: ImageProps): JSX.Element => {
    const [imageLoaded, setImageLoaded] = useState(false);
    const [errorLoadingImage, setErrorLoadingImage] = useState(false);
    return (
        <ImageContainer height={props.height} width={props.width}>
            {!imageLoaded && props.children}
            {!errorLoadingImage && (
                <LazyImage
                    onError={() => {
                        logger.debug(`Error loading image with src = ${props.src}`)
                        setErrorLoadingImage(true);
                    }}
                    afterLoad={() => {
                        setImageLoaded(true);
                    }}
                    alt={props.alt}
                    src={props.src}
                    height={props.height}
                    width={props.width}
                    visibleByDefault={props.visibleByDefault ?? false}
                    effect="opacity"
                />
            )}
        </ImageContainer>
    );
};

export default Image;

pedrovgs avatar Oct 14 '21 17:10 pedrovgs