I managed to get an array of refs of sections on my page that looks like this:
(6) [{…}, {…}, {…}, {…}, {…}, {…}]
0: {current: div.single-section}
1: {current: div.single-section}
2: {current: div.single-section}
3: {current: div.single-section}
4: {current: div.single-section}
5: {current: div.single-section}
length: 6
__proto__: Array(0)
I passed it from Sections component to CategoryNav component, where in Navbar I have categories that are corresponding to those sections. Every single-section has data-id that is equal to category id. Now, my goal is to, depending on what section is on screen give the corresponding category in navbar class "active". That all I did and it works. The problem which I have is this function on eventListener scroll that sets my state to data-id of single section which will give corresponding category with this id class "active" and that all I have done. The only problem I have is this function:
const activeCategory = () => {
for (let i = 0; i < myArr.length; i++) {
if (
window.pageYOffset > myArr[i].current.offsetTop &&
myArr[i].current.offsetTop < myArr[i].current.offsetTop + myArr[i].current.getBoundingClientRect().height
);
{
setCurrentCategory(myArr[i].current.dataset.id);
break;
}
}
};
I want to loop this array, and check if first section's is basically on the screen, if it is, it sets my state to dataset.id of this section, if it is not, it goes to next item. I wrote this, but it stays on first item, no mather what is on the screen, it just doesn't go to next item. Can anyone help?
question from:
https://stackoverflow.com/questions/65830540/loop-that-stops-when-condition-is-met-that-sets-state-depending-on-window-scrol 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…