Skip to content
Advertisement

Scroll to selected list item in material-ui

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?

Here is a demo sendbox link

After click on the item list should looks like this (selected item is in the center):

enter image description here

Advertisement

Answer

Hold a ref to the List, and upon click on ListItem, calculate how much you need to scroll based on:

  1. list item height
  2. the index of the selected item
  3. 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>
      );
    }
    

Edit Invisible Backdrop

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement