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 ?