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