Use a common function to handle change of the multiple array-based similar states on the user click in REACT

Viewed 60

I have created a transfer list in react which have two box for transferring names between each other. (Left list to Right list ). So i have written a function handleAllRight which transfers all the element in the left list to 2nd list which basically are array and make the left list empty serving the purpose of handleAllRight button. Now I introduced one more leftList2 and rightList2 which also have a handleAllRight functionality.

But i am not getting to write a common handleAllRight function for both of the list. The only thing in handleAllRight function which is different is the number of the list. This is my handleAllRight function in which i have used if loop. But how to dynamically create it if any list is passed in it. It should take care of the transfer checking the id on which the user clicked.

const handleAllRight = listNumber => {
if (listNumber === 1) {
  setRightlist1(leftlist1);
  setleftlist1([]);
}
if(listNumber === 2){
    setRightlist2(leftlist2)
    setleftlist2([]);
}
  };

But i do not want to use the condition as there could be many list so it would increase the size of the code lines. The other thing i tried is to use the eval function. Its working for any number of transfer list But i do not want to use the eval too as it is not good practice to use. For example i used eval like this

    const handleAllRight = listNumber => {
        eval(`setRightJobSeq${listNumber}(leftJobSeq${listNumber})`)
        eval(`setleftJobSeq${listNumber}([])`);
}

Here is the codeSandbox link. https://codesandbox.io/s/trusting-water-ccymg?file=/src/App.js

2 Answers

Using Eval is not a good idea. I think you can do this. You can pass leftList, and functions setleftlist1 or setleftlist2, setRightList1 or setRightList2 as the parameters and access the dynamic functions with this

 const handleAllRight = (leftList, setleftlist, setRightList) => {
       this[setRightList](leftList);
       this[setleftlist]([]);
      };

So basically you have an array of array of collections. This structure seems gpod for your code:

const myData = [
  {
    list1: [...],
    list2: [...],
  },
  {
    list1: [...],
    list2: [...] ,
  },
]

Then you can push into this collection, remove items, and access them by their index

Related