2

I want to be able to get the position of the scroll and automatically scroll a material-ui table (https://v4.mui.com/components/tables/#virtualized-table) so that when I leave the page and return, I could automatically scroll back to where I stopped.

Thank you.

1 Answer 1

1

Example that you sent uses package react-virtualized, which you have to install. The Table component which you can import from this package has onScroll prop.

Make a handler function with saving results to local storage, add ref to Table and call scrollToPosition method, such as:

import React, {useState, useRef, useEffect} from 'react';
import { Table, Column } from 'react-virtualized';
import {axios} from 'helpers';

function App() {

    const [data, setData] = useState([]);
    const ref = useRef();

    const {scrollTop} = JSON.parse(localStorage.getItem('data'));
    
    useEffect(() => {
        axios
            .get('https://random-data-api.com/api/address/random_address?size=100')
            .then(res => {
                setData(res);
                ref.current.scrollToPosition(scrollTop)
            })
    }, [scrollTop]);

    const handleScroll = data => {
        const {scrollTop} = data;
        if(scrollTop > 50) {
            localStorage.setItem('data', JSON.stringify(data))
        }
    };

    return (
        <Table
            ref={ref}
            rowCount={data.length}
            width={300}
            height={300}
            headerHeight={20}
            rowHeight={30}
            rowGetter={({index}) => data[index]}
            onScroll={handleScroll}
            scrollToIndex={10}
        >
            <Column label="City" dataKey="city" width={100} />
        </Table>
    )
}

P.S. Code may be unoptimized and have some errors.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.