Background
Wijmo provides React components for FlexGrid, including FlexGridColumnGroup for defining nested columns in JSX. Each group can use collapseTo to specify which child column stays visible when the group is collapsed, and isCollapsed to control its state.
Steps to Complete
- Define grouped columns in JSX.
- Add Collapse and Expand buttons.
- Update every column group.
Getting Started
Define grouped columns in JSX
Add collapseTo to each collapsible group and nest its columns inside it.
<FlexGrid
initialized={handleGridInitialized}
itemsSource={data}
autoGenerateColumns={false}
>
<FlexGridColumnGroup binding="name" header="Name" />
<FlexGridColumnGroup
header="Performance"
collapseTo="perf.ytd"
>
<FlexGridColumnGroup binding="perf.ytd" header="YTD" />
<FlexGridColumnGroup binding="perf.m1" header="1 M" />
<FlexGridColumnGroup binding="perf.m6" header="6 M" />
<FlexGridColumnGroup binding="perf.m12" header="12 M" />
</FlexGridColumnGroup>
<FlexGridColumnGroup
header="Allocation"
collapseTo="alloc.amount"
>
<FlexGridColumnGroup binding="alloc.stock" header="Stocks" />
<FlexGridColumnGroup binding="alloc.bond" header="Bonds" />
<FlexGridColumnGroup binding="alloc.cash" header="Cash" />
<FlexGridColumnGroup binding="alloc.amount" header="Amount" />
</FlexGridColumnGroup>
</FlexGrid>
collapseToidentifies the column that remains visible when its group is collapsed. Add the group’s other columns as nestedFlexGridColumnGroupcomponents.
Add Collapse and Expand buttons
Place the buttons in the same React component as the grid.
<button
type="button"
onClick={() => setAllGroupsCollapsed(true)}
>
Collapse
</button>
<button
type="button"
onClick={() => setAllGroupsCollapsed(false)}
>
Expand
</button>
-
The Collapse button passes
trueto the helper function. The Expand button passesfalse.
Update every column group
Store the FlexGrid instance from its initialized callback. Then walk through the groups and their nested children, setting isCollapsed on each group.
const gridRef = useRef(null);
const handleGridInitialized = (grid) => {
gridRef.current = grid;
};
const setAllGroupsCollapsed = (collapsed) => {
const grid = gridRef.current;
if (!grid) return;
grid.deferUpdate(() => {
const setGroupState = (groups) => {
groups.forEach((group) => {
if (group.columns && group.columns.length > 0) {
group.isCollapsed = collapsed;
setGroupState(group.columns);
}
});
};
setGroupState(grid.getColumnGroups());
});
};
getColumnGroups()provides the top-level groups. The helper recurses through each group’s child columns, so nested groups receive the same state.deferUpdatebatches the changes.
With this setup, users can click Collapse to collapse all configured column groups or Expand to show them again. When a group is collapsed, its collapseTo column remains visible. Nested groups are updated along with their parent groups.
Happy coding!
Andrew Peterson
