I would use useRef for dom manipulation in React. That will be optimized.
import { useLayoutEffect, useState, useRef, useEffect } from "react";
import { render } from "react-dom";
import classnames from "classnames";
import "./index.css";
const App = () => {
// const scrollingDiv = document.getElementById("scrollContainer");
// const img1 = document.getElementById("img1");
// const img2 = document.getElementById("img2");
const scrollingDiv = useRef(null);
const image1 = useRef(null);
const image2 = useRef(null);
useEffect(() => {
scrollingDiv.current.onscroll = function () {
if (scrollingDiv.scrollTop < 250) {
image1.current.src = "https://placeimg.com/250/100/arch";
image2.current.src = "https://placeimg.com/250/100/animals";
}
if (scrollingDiv.current.scrollTop > 500) {
image1.current.src = "https://placeimg.com/250/100/nature";
image2.current.src = "https://placeimg.com/250/100/people";
}
if (scrollingDiv.current.scrollTop > 1000) {
image1.current.src = "https://placeimg.com/250/100/tech";
image2.current.src = "https://placeimg.com/250/100/any";
}
};
}, []);
return (
<>
<div class="container">
<div class="left">
<img ref={image1} id="img1" src="https://placeimg.com/250/100/arch" />
<img ref={image2} id="img2" src="https://placeimg.com/250/100/animals" />
</div>
<div class="middle" ref={scrollingDiv} id="scrollContainer">
<div class="in-middle">
<div class="in-in-middle" id="1"></div>
<div class="in-in-middle" id="2"></div>
<div class="in-in-middle" id="3"></div>
</div>
</div>
</div>
</>
);
};
render(<App />, document.getElementById("root"));
Or you can put direct listeners on the element as well using onSroll prop.
Also, don't forget to clear all the listeners in useEffect cleaning function, that way, you won't have any memory leak issues.
scrollingDivis null because thegetElementById("scrollContainer")returns nothing. Since your component is not mounted, you wont have the div on the DOM. Try to put your code inuseEffect