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?
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'));