1

can you please tell me how to change data-src to src in react when it come in view port?I have 3 images I don't want to load at once .I want to do lazy loading .when It comes to view port I want to change data-src to src.But it is not working .

here is my code

import React, { useEffect } from "react";
import "./styles.css";
let data = [
  {
    src: "https://picsum.photos/600/600"
  },
  {
    src: "https://picsum.photos/600/600"
  },
  {
    src: "https://picsum.photos/600/600"
  }
];
export default function App() {
  useEffect(() => {
    let options = {
      root: null,
      rootMargin: "0px",
      threshold: 1.0
    };

    let target = document.querySelector(".lazy-load");
    let lazyloadImages = (entries, observer) => {
      entries.map((entry) => {
        if (entry.isIntersecting) {
          entry.target.src = entry.target.getAttribute("data-src");
        }
      });
      target.forEach((target) => observer.observe(target));
    };
    let observer = new IntersectionObserver(lazyloadImages, options);
  }, []);
  return (
    <div className="App">
      <div className="box">Box</div>
      {data.map((i) => {
        return <img className="lazy-load" data-src={i.src} src={""} />;
      })}
    </div>
  );
}

https://codesandbox.io/s/frosty-lovelace-yjfl9?file=/src/App.js:0-980

I am using Intersection Observer API https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

but it is not loading image why ?

user944513
  • 12,247
  • 49
  • 168
  • 318
  • You should work **with** React and *not modify the DOM* by yourself. Use some react state and update it accordingly when an image is in-view and then use that state in your JSX to conditionally switch between `data-src` and `src` *props* – vsync Dec 16 '20 at 07:47
  • https://github.com/onderonur/react-intersection-observer-hook – vsync Dec 16 '20 at 07:51
  • https://github.com/TejasQ/react-hook-intersection-observer – vsync Dec 16 '20 at 07:51
  • https://github.com/thebuilder/react-intersection-observer – vsync Dec 16 '20 at 07:51

0 Answers0