Last active
August 30, 2020 13:33
-
-
Save yongdamsh/aa03ef7f5875e7c9c334c3fff0c8f656 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { useEffect, useRef } from "react"; | |
| import ReactDOM from "react-dom"; | |
| import "./styles.css"; | |
| // Custom hook | |
| function useLazyImageObserver(target) { | |
| useEffect(() => { | |
| if (!target.current) { | |
| return; | |
| } | |
| let observer = new window.IntersectionObserver(entries => { | |
| entries.forEach(entry => { | |
| if (entry.isIntersecting) { | |
| const lazyImage = entry.target; | |
| lazyImage.src = lazyImage.dataset.src; | |
| observer.unobserve(lazyImage); | |
| } | |
| }); | |
| }); | |
| observer.observe(target.current); | |
| return () => { | |
| if (observer) { | |
| observer.disconnect(); | |
| observer = null; | |
| } | |
| }; | |
| }, [target]); | |
| } | |
| // Component | |
| function App() { | |
| const target = useRef(null); | |
| useLazyImageObserver(target); | |
| return ( | |
| <section> | |
| <div style={{ height: "2000px" }} /> | |
| <img ref={target} data-src="https://placeimg.com/320/100/any" alt="" /> | |
| </section> | |
| ); | |
| } | |
| const rootElement = document.getElementById("root"); | |
| ReactDOM.render(<App />, rootElement); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment