2

I have a table with a body size fixed as explained in the Material UI. I would like to listen to the scroll event of the table in order to load more rows.

Which is the best approach to listen to this scroll?

0

2 Answers 2

2

Tried the first solution which didn't work with my implementation.

I got this working using [email protected] and [email protected]:

Create a table element and set the ref to a name:

<Table>
    ...
    <TableBody ref="table-body">
        ...
    </TableBody>
</Table>

In componentDidMount, find the DOMNode using ReactDOM.findDOMNode:

componentDidMount() {
    let tableBodyNode = ReactDOM.findDOMNode(this.refs["table-body"]).parentNode.parentNode;

    tableBodyNode.addEventListener('scroll', (e) => {
        console.log(e);
    });
}

This will give you the scroll event of the table.

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

2 Comments

Is kind of weird the way we are handling this scroll listeners with parentNode.parentNode I remember I ended up using github.com/janpaepke/ScrollMagic but still not a good solution to fix this problem.
don't forget to remove the event listener in componentWillUnmount()
1

This is not straightforward and perhaps material-ui's Table is not the best suited for your requirements. You may want to take a look at some infinite-scrolling components, like react-infinite or react-list.

That being said, I experimented a bit and came up with this method of intercepting the scroll event in material-ui's TableBody.

First, capture a reference to the scrollable div that your table's body is contained in (its grandparent element in this case):

<Table height={200}>
  ...
  <TableBody
    ref={ref => { this.viewport = ReactDOM.findDOMNode(ref).parentNode.parentNode; } }>
  ...

then, in componentDidMount(), add an event listener for the onscroll event to the scrollable div:

componentDidMount() {
  this.viewport.addEventListener('scroll', (e) => {
    console.log(e);
  });
}

1 Comment

Is there way to scroll to bottom of the rows? I just tried to tweak your solution to set scrollTop. But it gave me the warning that Cannot read property 'parentNode' of null.

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.