T
TanStack•3y ago
exotic-emerald

How to scroll tanstack table to certain column by default

I have a large table with ~15 columns, Is it possible to implement a scrollTo mechanism that will allow me to the y scroll the table to athe certain column on the initial mount? I've tried with useRef() attached to <Table> but this didn't work. I've also tried to see if it's possible by directly accessing table or its children with document.getElementsByTagName('table')[0].scrollTo(...) in the console. Unfortunately, it did not. Do you have any idea how it could be done? Thank you.
1 Reply
exotic-emerald
exotic-emeraldOP•3y ago
Update: I've managed to do this by using query selectors and scrollIntoView If anyone has a better approach, feel free to post it 🙂
const tableRef = React.useRef<HTMLTableElement>(null);
// ...

React.useEffect(() => {
const scrollToColumn = (columnIndex: number) => {
if (!tableRef.current) {
return;
}

const column = tableRef.current.querySelector(
`thead th:nth-child(${columnIndex + 1})`
);
column?.scrollIntoView({
behavior: "smooth",
inline: "center",
});
};

const mediaQuery = window.matchMedia("(max-width: 768px)");
const isMobile = mediaQuery.matches;

if (isMobile && props.onMountScrollToColumnNumber) {
scrollToColumn(props.onMountScrollToColumnNumber);
}
}, [props.onMountScrollToColumnNumber]);

// ....

return (
<Table ref={tableRef}>
// ....
)
const tableRef = React.useRef<HTMLTableElement>(null);
// ...

React.useEffect(() => {
const scrollToColumn = (columnIndex: number) => {
if (!tableRef.current) {
return;
}

const column = tableRef.current.querySelector(
`thead th:nth-child(${columnIndex + 1})`
);
column?.scrollIntoView({
behavior: "smooth",
inline: "center",
});
};

const mediaQuery = window.matchMedia("(max-width: 768px)");
const isMobile = mediaQuery.matches;

if (isMobile && props.onMountScrollToColumnNumber) {
scrollToColumn(props.onMountScrollToColumnNumber);
}
}, [props.onMountScrollToColumnNumber]);

// ....

return (
<Table ref={tableRef}>
// ....
)

Did you find this page helpful?