beekai-oss / react-simple-img

🌅 React lazy load images with IntersectionObserver API and Priority Hints
MIT License
989 stars 41 forks source link

Image src not updated when component rerenders #64

Closed kmcaloon closed 5 years ago

kmcaloon commented 5 years ago

I have a filter which sorts through a list of data and renders components based on the selected value. Each component has a lazy image. When the page first loads and all of the components display their images load fine. But once I use the filter the components rerender with the placeholder images without the src updating. Am I missing an easy solution for this?

bluebill1049 commented 5 years ago

hi @kmcaloon,

I don't think to react simple img sort filter or change src, because all images have to be registered into intersection observer when page load. You may have to switch back to img tag when you want to set the src tag dynamically.

kmcaloon commented 5 years ago

Thanks, I firgured as much and came up with the following using a simple hook to make sure the full res image always shows after the component has originally mounted:

const Image = ( { customClassName, src, ...props } ) => {

  const imageSrc = src;
  const placeholder = 'placeholder-image.jpg'; // Example
  const [ isLoaded, setIsLoaded ] = React.useState( false );

  React.useEffect( () => {
    setIsLoaded( true )
  }, [] );

  /* ------ = Output = --------------------------------------------------------------------- */

  const className = classnames( 'Img', customClassName );

  return(

    <SimpleImg
    className={ className }
    src={ src }
    placeholder={ isLoaded ? src : placeholder }
    { ...props }
    />

  );

};

export default Image;
bluebill1049 commented 5 years ago

nice one :)

Alfrex92 commented 4 years ago

hi @kmcaloon,

I don't think to react simple img sort filter or change src, because all images have to be registered into intersection observer when page load. You may have to switch back to img tag when you want to set the src tag dynamically.

The first time that the page loads? or when the full page(App component) renders?