I have an items object
const items = [
{
dataField: 'A',
children: undefined
},
{
dataField: 'B',
children: [
{
dataField: 'B0',
dataField: 'B1',
dataField: 'B2',
}
]
},
{
dataField: 'C',
children: undefined
},
]
I have a Checkbox component
<Checkbox onChange={(e) => {
const data = item.children && item.children.map(child => child.dataField)
toggleColumnDisplay(e.currentTarget.checked, data ? [item.dataField, ...data] : item.dataField)}}
/>
Every time it is checked on or off, it checks if the item object has a children property and sends the appropriate arguments to the toggleColumnDisplay function.
Ex 1)
{
dataField: 'A',
children: undefined
}
is checked/unchecked. data = undefined and the string 'A' is sent
Ex 2)
{
dataField: 'B',
children: [
{
dataField: 'B0',
dataField: 'B1',
dataField: 'B2',
}
]
}
is checked/unchecked. data = ['B0', 'B1', 'B2'] and the array ['B', 'B0', 'B1', 'B2'] is sent
I have a showCheckColumn state that is an array of strings
this.state = {
showCheckColumn: []
}
The toggleColumnDisplay function does the following
toggleColumnDisplay = (value: boolean, dataField: string | Array<string>): void => {
if (value) {
if (typeof dataField === 'string') {
this.setState({ showCheckColumn: [...this.state.showCheckColumn, dataField] })
} else {
this.setState({ showCheckColumn: [...this.state.showCheckColumn, ...dataField] })
}
} else {
if (typeof dataField === 'string') {
this.setState({ showCheckColumn: this.state.showCheckColumn.filter(item => item !== dataField) })
} else {
this.setState({ showCheckColumn: this.state.showCheckColumn.filter(col => !dataField.includes(col)) })
}
}
}
For Ex 1) checked toggleColumnDisplay receives a value of true and a dataField type of string
For Ex 1) unchecked toggleColumnDisplay receives a value of false and a dataField type of string
For Ex 2) checked toggleColumnDisplay receives a value of true and a dataField type of object
For Ex 2) unchecked toggleColumnDisplay receives a value of false and a dataField type of object
The problem is that showCheckColumn should always be ordered by the index of the original items array.
In the original items array,
the object with dataField: 'A' has an index of 0
the object with dataField: 'B' has an index of 1
the object with dataField: 'C' has an index of 2
But toggleColumnDisplay does not retain this original order and will always move what was checked/unchecked to be last in the array with every setState.
For example if I check uncheck the object with dataField: 'B',
In the showCheckColumn state
the object with dataField: 'A' has an index of 0
the object with dataField: 'C' has an index of 1
the object with dataField: 'B' has an index of 2.
How do I retain my original order when I check/uncheck each item?