In my react app I have columns that display data in a grid format, with two different views (isSelecting && the default view) and each column has a draggable handle that can resize the width. When the user clicks select mode a checkbox is added to the front of the columns array of objects.

I have a function that saves to state the width of the column after the user resizes it, to the correct index of the column. (User drags handle of first column, will save that new width to the 0 indexed column).
overrideColumnWidth = (columnIndex, newWidth) => {
this.setState({
columnWidthOverrides: {
...this.state.columnWidthOverrides,
[columnIndex]: newWidth
}
});
I also have a function that looks something like this where if the grid is in select mode, create a new object that has values set to an incremented index, due to the checkbox being added in select mode and not wanting the checkbox column to carry over the modified width. A done state is kept to prevent this function from being called multiple times. After my columnWidthOverrides state will look like the two examples below
columnWidthOverrides = { 0: 400, 1: 500, 2: 600}
columnWidthOverridesSelectMode = { 0: undefined, 1: 400, 2: 500, 3: 600}
componentWillUpdate(nextProps) {
if (nextProps.isSelecting && !this.state.done) {
const { columnWidthOverrides } = this.state;
const columnIndexes = Object.keys(columnWidthOverrides);
const incrementedIndexes = columnIndexes.map((index) => ({
[`${Number(index) + 1}`]: columnWidthOverrides[Number(index)]
}));
const incrementedColumns = incrementedIndexes.reduce((map, columnWidthOverrides) => ({
...map, ...columnWidthOverrides }),{});
this.setState({
done: !this.state.done,
columnWidthOverrides: {
...incrementedColumns
}
});
}
}
My problem currently is that although the select view will correctly have the correct column widths, once the user changes the grid back to non select mode, the widths need to revert back to the previous state ex. {0: 400, 1: 500, 2: 600}. Is there a way to revert state back to a previous state? I've tried setting it back in the componentWillMount function but it causes an infinite loop and setstate is called multiple times automatically breaking the app.
Try to catch the mode change event - 'non-select-mode'
Then execute a function to restore current state values to default.
Try adding 1 entry to the object -
default: function(){
this.columnWidthOverrides = {
0: 400, 1: 500, 2: 600
}
}
Then, when user change to non select mode, execute -
this.default();