2

Using Ant Design Table, how can can I programmatically scroll (I'm using scroll:y) a row into view given it's row key to ensure that it is visible?

TheLazyDogsBack
  • 197
  • 1
  • 11

2 Answers2

3

Option 1:

use document.querySelector('div.ant-table-body').scrollTop = rowIndex * 50

if row height is stable, example usage 55px

Check the working stackblitz.

(see antd issue Scroll to row of virtual table )

class App extends React.Component {
  handleScroll = () => {
    document.querySelector('div.ant-table-body').scrollTop = 20 * 55;
  };

  render() {
    return (
      <div>
        <p>
          <Button type="primary" onClick={this.handleScroll}>
            Scroll
          </Button>
        </p>
        <Table
          columns={columns}
          dataSource={data}
          pagination={{ pageSize: 50 }}
          scroll={{ y: 240 }}
        />
      </div>
    );
  }
}

Option 2:

Use the third party lib scroll-into-view togehter with rowClassName.

Check attached codesandbox and the corresponding antd issue Scroll the table to the specified row.

import React from 'react';
import { render } from 'react-dom';
import 'antd/dist/antd.css';
import { Table, Button } from 'antd';
import scrollIntoView from 'scroll-into-view';

const columns = [
  {
    title: 'Name',
    dataIndex: 'name',
    width: 150,
  },
  {
    title: 'Age',
    dataIndex: 'age',
    width: 150,
  },
  {
    title: 'Address',
    dataIndex: 'address',
  },
];

const data = [];
for (let i = 0; i < 100; i++) {
  data.push({
    key: i,
    name: `Edward King ${i}`,
    age: 32,
    address: `London, Park Lane no. ${i}`,
  });
}

class App extends React.Component {
  handleScroll = () => {
    scrollIntoView(document.querySelector('.scroll-row'), {
      align: {
        top: 0,
      },
    });
  }

  render() {
    return (
      <div>
        <p>
          <Button type="primary" onClick={this.handleScroll}>Scroll</Button>
        </p>
        <Table
          rowClassName={(record, index) => (index === 20 ? 'scroll-row' : '')}
          columns={columns}
          dataSource={data}
          pagination={{ pageSize: 50 }}
          scroll={{ y: 240 }}
        />
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));
zerocewl
  • 11,401
  • 6
  • 27
  • 53
1

Just in case it's useful, here's the TS code to lookup the row by key and scroll if you have a dependency that changes the current selection:

useEffect(() => {
        const rows = document.querySelector('.your-antd-table')
                      ?.getElementsByClassName('ant-table-row');
        if (!rows) return;
        const myRowKey = f(stuffNeededToFindYourRowKey);
        const target = _.find(rows, 
            r => r.getAttribute('data-row-key') === myRowKey);
        if (!target) return;
        scrollIntoView(target as HTMLElement);
    }, [stuffNeededToFindYourRowKey])
TheLazyDogsBack
  • 197
  • 1
  • 11