Managing a dynamic grid with varying numbers of rows and 3-5 cards per row can be complex, especially when using useSelector and .map to populate the data for each card. The initial state includes multiple key/value pairs, some unique to each record. Visualizing this in a console.log may look like:
[ 0: {Key: 1, PerformanceYR: "2019", SubRegionKey: 24, showDetail: false},
1: {Key: 2, PerformanceYR: "2019", SubRegionKey: 24, showDetail: false},
2: {Key: 3, PerformanceYR: "2019", SubRegionKey: 24, showDetail: false} ]
The goal is to update the 'showDetail' property from false to true for a specific record when clicking on a button associated with that record's key. However, current implementations are affecting all records rather than just the targeted one. Here is a snippet of the relevant code:
const ServiceAreaTile = () => {
const psOverviewSA = useSelector((state) => state.psOverviewSA);
const classes = useStyles();
const [detail, setDetail] = useState(false);
const handleChange = (event, data) => {
let index = psOverviewSA.findIndex(item=> item.Key === event.currentTarget.id)
let newArray = [...psOverviewSA]
setDetail(!newArray[index].showDetail)
}
return psOverviewSA.map((data) => {
data.showDetail = detail;
return (
// Code for displaying the grid and cards
)
The issue arises when trying to change 'showDetail' based on the clicked button's id matching a key in the data set. Instead of only affecting that specific record, the current implementation alters all 'showDetails'. Further tweaking needs to be done at the button level:
<Button id={data.Key} onClick={(event, data) => handleChange(event, data)} >
<ExpandMoreIcon />
</Button>
To render additional details for records with 'showDetail' set to true, the following code section comes into play:
{data.showDetail && <div><Typography>{data.SubRegionKey}</Typography></div>}
Diving into the complexities of associating the handleClick function with useState versus useSelector reveals nuances that impact the functionality. While immediate solutions seem elusive, perseverance will eventually lead to a breakthrough. Stay patient in the journey towards resolving these challenges!