admin管理员组文章数量:1122832
I have a scroll based fetch by incrementing the page number when the last index item in the array reaches the bounds of the window on the x axis.
This all works fine. It works for drag scroll and key events.. I also have pagination buttons that can increment the page number for the fetch, the new data is added to the array.
Now I have implemented scroll to for the clickable pagination and the [0]
index of each new index set is the item that is supposed to be scrolled to which works BUT:
The scroll to only works when there are 40 index items or less in the DOM. When there are more than 40 index items, my code logs that the item can not be found in the DOM... which is nonsense because I can drag or scroll to it and SEE it!
My question is HOW can I manage this?! Is there a way I can deal with this?
WHY is it behaving in this way! the items ARE available and CAN be manually scrolled to, just not using scrollTo
One idea I had is to select only 40 items every render , so if the user selects page x then the 20 index items from that fetch are displayed with another 10 items either side from the prev or next IF they exist.
I have tried limiting the array to 40 items BUT that interferes with the drag / scroll and causes issues with refetch for some reason!
import React, { useEffect, useState, useRef } from 'react';
import axios from 'axios';
import { moviePopular } from '../../api/tmdb';
import { TMDB_IMAGE_ENDPOINT } from '../../api/tmdb';
import { gsap } from 'gsap';
import { Draggable } from 'gsap/Draggable';
import styled from "styled-components";
import { useContext } from 'react';
import { DragContext } from '../../contexts/dragContext';
import { ScrollToPlugin } from 'gsap/ScrollToPlugin';
gsap.registerPlugin(ScrollToPlugin);
gsap.registerPlugin(Draggable);
const CardContainer = styled.div`
border: 2px solid rgba(255, 255, 255, 0.2);
border-radius: 10px;
overflow: hidden;
width: 10rem;
height: 15rem;
display: flex;
margin-right: 2rem;
`;
const PosterImage = styled.img`
width: 100%;
height: 100%;
object-fit: cover;
`;
function ListPopular({ isDragCss, page, setPagePopular, popular, setPopular, pagePopular, setFirstItem, firstItem }) {
const { dragState, setDragState } = useContext(DragContext);
const [isLatched, setIsLatched] = useState(false);
const [firstItemArray, setFirstItemArray] = useState([])
const [res, setRes] = useState([])
const popularRef = useRef(null);
const itemRef = useRef(null);
const iDs = useRef(new Set())
const fetchPopular = () => {
axios.get(moviePopular(pagePopular))
.then((res) => {
setRes(res?.data)
setPopular((prev) => ({...res.data,
results: [...(prev?.results || []),
...res.data.results.filter((movie) =>
!iDs.current.has(movie.id)
&& iDs.current.add(movie.id)),
],
}))
})
.catch((err) => {
console.error('Error fetching popular movies:', err);
});
};
useEffect(() => { fetchPopular() }, [pagePopular])
useEffect(() => {
if (isLatched) {
const timer = setTimeout(() => { setIsLatched(false) }, 300)
return () => clearTimeout(timer)
}
}, [isLatched]);
useEffect(() => {
const handleScroll = () => {
const element = popularRef.current;
if (!element) return;
const scrollX = element.scrollLeft;
const maxScrollLeft = element.scrollWidth - element.clientWidth;
if (!isLatched) {
if (scrollX >= maxScrollLeft) {
console.log('Increment Page!', pagePopular, 'Scroll', scrollX);
if (pagePopular < 500) {
setDragState(true)
setIsLatched(true);
setPagePopular(pagePopular + 1);
}
} else if (scrollX <= 0) {
console.log('Decrement Page!', pagePopular, 'Scroll', scrollX);
if (pagePopular > 1) {
setDragState(true)
setIsLatched(true);
setPagePopular(pagePopular - 1);
}
}
}
}
const container = popularRef.current;
container?.addEventListener('scroll', handleScroll);
return () => {
container?.removeEventListener('scroll', handleScroll);
};
}, [isDragCss, popular, isLatched]);
useEffect(() => {
if (isDragCss && popularRef.current) {
const container = popularRef.current;
Draggable.create(container, {
type: 'scrollLeft',
edgeResistance: 1,
bounds: {
minX: 0,
maxX: container.scrollWidth - container.clientWidth,
},
inertia: true,
onDrag: () => setDragState(true),
});
return () => {
const draggableInstance = Draggable.get(container);
draggableInstance?.kill();
};
}
}, [isDragCss]);
useEffect(() => {
const handleKeyDown = (e) => {
const container = popularRef.current;
if (!container) return;
if (e.key === 'ArrowRight') {
setDragState(true)
container.scrollBy({ left: 50, behavior: 'smooth' });
} else if (e.key === 'ArrowLeft') {
container.scrollBy({ left: -50, behavior: 'smooth' });
setDragState(true)
}
};
window.addEventListener('keydown', handleKeyDown);
return () => {
window.removeEventListener('keydown', handleKeyDown);
};
}, []);
const handleItem = () => {
if (firstItem.drag) {
console.log('DRAGGING!');
return;
}
const itemExist = popular?.results?.findIndex(item => item.id === firstItem.id);
if (itemExist !== -1 && itemRef.current?.children?.[itemExist]) {
console.log('Item Exist!', itemExist);
itemRef.current.children[itemExist].scrollIntoView({
behavior: 'smooth',
block: 'start',
});
} else {
console.warn('Item not found or not yet rendered in the DOM.');
}
};
useEffect(() => {
setFirstItem( { drag: dragState, page: pagePopular, id: res?.results?.[0]?.id })
setDragState(false);
}, [popular]);
useEffect(() => {
setTimeout(() => {
handleItem();
}, 500);
}, [popular]);
useEffect(()=>{
console.log(res?.results?.[0]?.id)
console.log(popular?.results)
console.log('First Item:', firstItem.drag , firstItem.page , firstItem.id )
},[popular])
return (
<div className="overflow-x-auto mt-8 mb-8 pt-4 pb-4 scrollbar-hidden max-w-full scroll-area" style={{ scrollSnapAlign: 'start' }}>
<ul className={`flex ${isDragCss ? 'nowrap' : 'wrap'} flex-row`} ref={popularRef}>
{popular?.results?.map((item) => (
<li key={item.id} className="mr-8" ref={itemRef}>
<CardContainer>
<PosterImage
src={`${TMDB_IMAGE_ENDPOINT}/${item?.poster_path}`}
alt={item.title}
/>
</CardContainer>
</li>
))}
</ul>
</div>
);
}
export default ListPopular;
本文标签: reactjsScrollTo fails with more that 40 index itemsStack Overflow
版权声明:本文标题:reactjs - ScrollTo fails with more that 40 index items - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736311287a1934684.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论