I have an antd list displayed on a page and certain actions elsewhere will cause an item in the list to be selected. I want the item to automatically scroll to it. I can’t figure it out.
The code that displays the list is below.
<List
itemLayout="horizontal"
dataSource={courses}
className="hoverable-list"
bordered
renderItem={(item, index) => (
<List.Item bordered="true" className={currentCourse == item.course_code ? 'active' : ''} onClick={() => setCurrentCourse(item.course_code)}>
{/* <Tooltip placement="bottomLeft" title={item.description}> */}
<List.Item.Meta
id={item.course_code}
title={item.course_code}
description={item.course_name}
/>
{/* </Tooltip> */}
</List.Item>
)}
/>
I tried using a getElementByID and then scrolling it into view, but that didn’t seem to do it.
const scrollToItem = (itemId) => {
const element = document.getElementById(itemId);
if (element) {
element.scrollIntoView({ behavior: 'smooth' });
}
};
const handleNodeClick = (nodeId) => {
setCurrentCourse(nodeId);
scrollToItem(nodeId);
}
2
Answers
You need to create a scrollable container for the list. Scroll in the container rather than the HTML document
e.g.
stackblitz
https://stackblitz.com/edit/stackblitz-starters-tuw9cm?file=src%2FApp.tsx