Aljullu / react-lazy-load-image-component

React Component to lazy load images and components using a HOC to track window scroll position.
https://www.npmjs.com/package/react-lazy-load-image-component
MIT License
1.46k stars 110 forks source link

Use placeholder prop with opacity effect #62

Open jotamodesto opened 4 years ago

jotamodesto commented 4 years ago

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" />

pedrovgs commented 3 years ago

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;