I have a list, build with material-ui. There are a lot of items in it, so scrollbar is visible.
What I would like to do is scroll to the selected item. Have any ideas of how to implement this?
After click on the item list should looks like this (selected item is in the center):
Advertisement
Answer
Hold a ref to the List, and upon click on ListItem, calculate how much you need to scroll based on:
- list item height
- the index of the selected item
number of visible list items.
JavaScriptx21211const scrollableListRef = React.createRef();
2
3function Row(props) {
4const { index, style } = props;
5
6const placeSelectedItemInTheMiddle = (index) => {
7const LIST_ITEM_HEIGHT = 46;
8const NUM_OF_VISIBLE_LIST_ITEMS = 9;
9
10const amountToScroll = LIST_ITEM_HEIGHT * (index - (NUM_OF_VISIBLE_LIST_ITEMS / 2) + 1) ;
11scrollableListRef.current.scrollTo(amountToScroll, 0);
12}
13
14return (
15<ListItem button style={style} key={index}
16onClick={() => {placeSelectedItemInTheMiddle(index)}}>
17<ListItemText primary={`Item ${index + 1}`} />
18</ListItem>
19);
20}
21