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.
const scrollableListRef = React.createRef(); function Row(props) { const { index, style } = props; const placeSelectedItemInTheMiddle = (index) => { const LIST_ITEM_HEIGHT = 46; const NUM_OF_VISIBLE_LIST_ITEMS = 9; const amountToScroll = LIST_ITEM_HEIGHT * (index - (NUM_OF_VISIBLE_LIST_ITEMS / 2) + 1) ; scrollableListRef.current.scrollTo(amountToScroll, 0); } return ( <ListItem button style={style} key={index} onClick={() => {placeSelectedItemInTheMiddle(index)}}> <ListItemText primary={`Item ${index + 1}`} /> </ListItem> ); }