Home > other >  React Native toggle add/remove element in an array based off toggling a button
React Native toggle add/remove element in an array based off toggling a button

Time:03-12

I have a TouchableOpacity that can be both pressed and unpressed.

Here is my useState variable:

const [isPressMonday, setIsPressMonday] = useState(false);

and here is my toggling function:

    setIsPressMonday(!isPressMonday);
    setDays(days => [...days, 'Monday']) 

  };

The thing is, when a user un-clicks the button, it should remove Monday from the array. This would be simple if I could just check if(!isPressMonday) and remove it from the array, but the default is false so that is almost always true

CodePudding user response:

You don't need to check with isPressMonday state instead check if 'Monday' present in days state. If yes, remove else, add.

//assuming 'days' is your array state name
setIsPressMonday(isPressMonday => !isPressMonday);
const index = days.indexOf('Monday');
if (index !== -1) {
  let tempDays = days
  tempDays.splice(index, 1);
  setDays(tempDays)
}
else {
  setDays(days => [...days, 'Monday'])
}
  • Related