Simple Component with background image LazyLoad

Hi! Here simple component which uses @frontity/hooks/use-in-view to lazyload component background-image

In β€œsrc” prop - the src of image to lazy load in background
In β€œTag” - the html tag prop to use in component

import useInView from "@frontity/hooks/use-in-view";

export const LazyBackground = ({ children, src, Tag = "div", ...rest }) => {

  const { ref, inView } = useInView({ triggerOnce: true });

  return (
    <Tag
      ref={ref}
      style={inView ? { backgroundImage: `url(${src})` } : {}}
      {...rest}
    >
      {children}
    </Tag>
  );
};
2 Likes

Thanks for sharing :blush:

1 Like

Hi, thanks for your snippet. Could you please show me how to use it in a component? I get a β€œCannot convert undefined or null to object” error.

I’m using it like so

<LazyBackground src={source_url} Tag="div" />

Thanks