I have a component List, which takes in props and renders a list. It has a prop named onReorder, which is a callback function passed from the parent, and is called when the list header is clicked.
List.js
const List = ({ title, size, columns, data, length = 10, showIndex, onReorder }) => {
console.log(data)
return (
// ... render list
<ListHeader onClick={onReorder}>Some Header Text</ListHeader>
)
}
data is a 2d array.
When onReorder is called, it sorts data and calls setData to update the order of the array.
Parent.js
const onReorder = (newOrder) => {
setData(sortData(data, newOrder))
}
// ...
return (
<List
// key={ MD5('list' + JSON.stringify(order)) } // to ensure that the list is rendered
size="col-12" length={ 10 } showIndex
title={ <>Title</> }
columns={ listColumns }
data={ data }
onReorder={ onReorder }
/>
)
This worked well, until I tried to map data for some styling:
return (
<List
// key={ MD5('list' + JSON.stringify(order)) } // to ensure that the list is rendered
size="col-12" length={ 10 } showIndex
title={ <>Title</> }
columns={ listColumns }
data={ data.map(d => [
<Link to={`/d/${ d[6] }`}>{ d[0] }</Link>,
d[1],
<HealthIndicator level={ d[2] }/>,
<Temperature>{ d[3] }</Temperature>,
<Status enabled={ d[4] } />,
d[5]
]) }
onReorder={ onReorder }
/>
)
When I press on the header, onReorder does fire, and the list is sorted (made sure by console logging). Moreover, the console.log(data) in List showed the not-updated data.
I also tried console logging directly in the data.map(d => {console.log(d); ...}), and it is showing the correct order, while the console.log(data) in List is still the previous one.
I also tried changing the data.map() to data.map(d => d), which shouldn't change anything, but it still shows the wrong order in List.
So to summarize, this works:
data={ data }
but this doesnt:
data={ data.map(d => d) }
The only reasons I could think of are:
- Array is sending address instead of value.
- I tried copying the array with
data=[...data], didn't do the job.
- Child is not rendering.
- I tried adding a unique key (as shown above), which still didn't fix the problem. Also, console.log(data) is being called in
List.
I have already tried everything in my mind and spend hours looking into this and I'm running out of options. Any thoughts or advice is appreciated. I'll provide more code and description if the above code is insufficient.
Thanks in advance :(