I have a grid with multiple cells that the user can select.
Depending on the cells the user selects on the grid, I show different actions at the bottom of the page. The way I’m implementing this right now is as such:
const allActionsToShow = {
action1: false,
action2: false,
action3: false,
action4: false
};
selectedCells.map(cell => {
if (cell.id === ‘cell1’) {
allActionsToShow.action1 = true;
allActionsToShow.action2 = true;
hideRemainingActions([‘action3’, ‘action4’]);
}
if (cell.id === ‘cell3’) {
allActionsToShow.action3 = true;
hideRemainingActions([‘action1’, ‘action2’, ‘action4’])
}
if (cell.id === ‘cell4’) {
allActionsToShow.action4 = true;
hideRemainingActions([`action1’, `action2`, action3’])
}
});
const hideRemainingActions = (actionsToHide: string[]) => {
actionsToHide.map(actionId => {
allActionsToShow[actionId] = false;
});
};
Is there a more efficient way of doing this? If there are 50 actions for example, then I have to manually set those 50 to true
depending on the cell selected (if
conditions above) and then pass in the actions I don’t want to show to the hideRemainingActions
function. This would make it difficult to scale.
2
Answers
I would probably do it a bit differently.. since you tagged
reactjs
I wrote up a rough component that you might be able to make use of.First, you’re using
map
to iterate through theselectedCells
list, butmap
returns an array that you’re not using, so it’s not exactly the right tool for the job here. Instead I’d just loop through the array using aforEach
.I’d define an object that specificies the permissions for each cell, and I’d do it outside the component so it didn’t get redefined on every render, or need to be passed to
useEffect
and such.I’d have a piece of state for the permitted actions, and I’d set them accordingly..
Finally, somewhere in the return, I’d only print the actions that were still permitted.
EDIT: I thought of another way to do it that I like better because it doesn’t require iterating through the entire list of cells on every click.. This might be more efficient. I’ll keep the original idea at the bottom.
Here’s the new idea
Here’s the old idea
such function may help if I understood well what you want to do this function receives an array
keysToSetToTrue
where each element is a string indicating the name of the key we want to set it totrue
first we copy the object then we set all its keys values to
false
since it will be overridden each timehideRemainingActions
runs, after that we map throughkeysToSetToTrue
array and set each corresponding key value ofupdateddActions
totrue
, then, we just need to return an array where each element is the name of the key we want to hide so we can pass directly the result of this function tohideRemainingActions
Try it