bvaughn / react-window

React components for efficiently rendering large lists and tabular data
https://react-window.now.sh/
MIT License
15.48k stars 778 forks source link

Is there a way to autoscroll to the bottom of the list #726

Open B-R-Bender opened 1 year ago

B-R-Bender commented 1 year ago

Hello everyone!

Thanks for amazing library.

Could you please guide me on one specific behaviour - I'm using VariableSizeList to display real-time logs. I'm wondering is there a good way to auto scroll to the bottom of the list unless user scrolls up, and then if user will manually scroll to the bottom - restore autoscroll to follow recent messages again? My list is limited to 5000 messages.

Regards.

robkozura commented 11 months ago

I searched the closed issues and came across this that might help: https://github.com/bvaughn/react-window/issues/573

cvvkshcv commented 11 months ago

I think this might help @B-R-Bender

  const myref = useRef(null);
  const Row = ({ index, style }) => (
    <div className={index % 2 ? "ListItemOdd" : "ListItemEven"} style={style}>
      Row {index}
    </div>
  );

  const showRef = () => {
    myref.current._outerRef.scrollTop = myref.current._outerRef.scrollHeight;
  }

  return (
    <div className="App">
      <h1 onClick={showRef}>Hello world</h1>
      <FixedSizeList
        className="List"
        height={300}
        itemCount={5000}
        itemSize={35}
        width={500}
        initialScrollOffset={400}
        ref={myref}
      >
        {Row}
      </FixedSizeList>
    </div>
  );
}

Approach:

  1. Pass a ref to your virtual-scroll component
  2. The component internally maintains _outerRef which points to the wrapper div which has scroll
  3. Access the element and set the scrollTop position to scrollHeight of the div which moves your cursor to the end.

Cheers ✌️