'How to calculate and set defaultColumn Width in react-table?
I am trying to set columns width dynamically so the sum of the columns width occupy the entire width of the table. I have a react-table component with dynamic width (takes 100% of its parent width), I divide the width by columns.length and set the following:
const defaultColumn = useMemo(
() => ({
width: columnWidth > 0 ? columnWidth : 150,
}),
[columnWidth]
);
const tableInstance= useTable(
{
columns: columnsTable,
data: dataTable,
defaultColumn: defaultColumn,
},
useGlobalFilter,
useSortBy,
usePagination,
useBlockLayout
);
when I console log the defaultColumn it gives me the correct calculated width, but the table cells always show 150px. why the table is not showing the defaultColumn width value? and how can I do this correctly?
Solution 1:[1]
As I see, changes in the defaultColumn doesn't trigger rebuilding of your columns definition.
So, to fix it, I propose making your columns definition dependent on defaultColumn value.
const defaultColumn = useMemo(
() => ({
width: columnWidth > 0 ? columnWidth : 150,
}),
[columnWidth],
);
// Here we make our columns definition to be related on defaultColumn value.
const columns = useMemo(() => {
// We recreate columnsTable array to create a new reference to table columns value by creating a new array.
return [...columnsTable];
}, [defaultColumn]);
const tableInstance = useTable(
{
columns,
data: dataTable,
defaultColumn: defaultColumn,
},
useGlobalFilter,
useSortBy,
usePagination,
useBlockLayout,
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pavlo Zhukov |
