[BUG] Items map does not reflect current state of ScrollMenu children
See original GitHub issueDescribe the bug
In my project, we have a use case to add & remove items from a ScrollMenu. When adding to the end of the collection, the ScrollMenu will correctly render the new item, but the items
and isLastItemVisible
api for the ScrollMenu
seem to be behind, causing the RightArrow component not to be rendered, even though it should. We are also using a hook on the new apiRef
to detect changes in the size of apiRef.current.items.size
to automatically scroll to the end of the collection on adding a new item, and this also does not seem to work because the items
map has not correctly been updated.
Additional Context
To start, we have 5 placeholder items in the ScrollMenu, and those get removed as we add items to the actual collection. As I mentioned, we also have functionality that will add and remove from the items
collection.
Here is an example of the code for reference:
const scrollMenuApiRef = useRef({});
const prevMenuItems = usePrevious(scrollMenuApiRef?.current?.items?.size);
const placeholderItems = [];
if (items.length < 5) {
for (let i = 0; i < 5 - items.length; i++) {
placeholderItems.push(
<PlaceholderItem
key={`placeholder-${i}`}
itemId={`carousel-list-${items.length - i}`}
/>
);
}
}
useEffect(() => {
if (scrollMenuApiRef.current.items.size > prevMenuItems) {
scrollMenuApiRef.current.scrollToItem(
scrollMenuApiRef.current.getItemById(items[items.length - 1].id), 'smooth', 'end', 'nearest'
);
}
}, [scrollMenuApiRef?.current?.items?.size]);
return (
<ScrollMenu
LeftArrow={LeftArrow}
RightArrow={RightArrow}
wrapperClassName={classes.wrapper}
apiRef={scrollMenuApiRef}
>
{items.map((item) => (
<Item
key={`carousel-list-${item.id}`}
itemId={item.id}
/>
))}
{placeholderItems}
</ScrollMenu>
);
Issue Analytics
- State:
- Created 2 years ago
- Comments:8 (6 by maintainers)
Top GitHub Comments
Ok, added
getItemElementById
andgetItemElementByIndex
helpers.@asmyshlyaev177, this solution seems to work well! Thank you for your help here. Would it be worth adding an
scrollToItemByItemId
to the public api? It seems like a common scenario to know an item id from outside of the context of theScrollMenu
, and thescrollToItem(getItemById(...))
combination seems less reliable without access to the most recentScrollMenu.items
.