react-sumail-lazy

1.0.0 • Public • Published

a tiny lazyload library made by miracle_sumail, use IntersectionObserver API to accompanish this functionality

1. see the code inside, make use of react hooks

const LazyBox: React.FC<any= ({className, children, threshold}) => {
      const ref: any = useRef(null);
      let [visible, setVisible] = useState(false);
     // let [io] = useObserver({visible, setVisible});
 
      const io = useMemo(() => (new IntersectionObserver((entries) => {
        console.log(entries);
        if(entries[0].isIntersecting && !visible){
             setVisible(!visible)
        }
            
        console.log(visible);
        if(!entries[0].isIntersecting && visible) {
             setVisible(false)
        }             
      }, {
         threshold
      })), [visible])
     
      useEffect(() => {
          io.observe(ref.current);
          return () => {
              console.log('finish');
              io.unobserve(ref.current);
          };
      }, [visible])
 
      return <div className={className} ref={ref}>
             {visible ? children : null}
      </div>
}

just a total of 34 lines, so tiny...

2. how to use

 render() {
        return (
             <>
                <LazyBox className={'lazybox'} threshold={[.2]}>
                    <div>fwegwgwgg</div>
                </LazyBox>
             </>
        )
    }

Readme

Keywords

none

Package Sidebar

Install

npm i react-sumail-lazy

Weekly Downloads

1

Version

1.0.0

License

ISC

Unpacked Size

2.91 kB

Total Files

3

Last publish

Collaborators

  • miracle_sumail