Toggle Number Selection in State Array

PHOTO EMBED

Thu Oct 31 2024 10:37:51 GMT+0000 (Coordinated Universal Time)

Saved by @desiboli #javascript #typescript #react.js

import React from 'react';

/**
 * Toggles the presence of a number in the selectedNumbers array state.
 *
 * @param number - The number to toggle in the selection.
 * @param setSelectedNumbers - The state setter function from useState.
 */
const toggleNumber = (
  number: number,
  setSelectedNumbers: React.Dispatch<React.SetStateAction<number[]>>
): void => {
  setSelectedNumbers((prevSelectedNumbers) => {
    if (prevSelectedNumbers.includes(number)) {
      // Number is already selected; remove it from the array
      return prevSelectedNumbers.filter((n) => n !== number);
    } else {
      // Number is not selected; add it to the array
      return [...prevSelectedNumbers, number];
    }
  });
};

// Initialize State in Your Component
const [selectedNumbers, setSelectedNumbers] = useState<number[]>([]);

// Use the toggleNumber Function
// Example usage within a component event handler
const handleNumberClick = (number: number): void => {
  toggleNumber(number, setSelectedNumbers);
};

// Implement in JSX
<button onClick={() => handleNumberClick(5)}>
  {selectedNumbers.includes(5) ? 'Deselect 5' : 'Select 5'}
</button>
content_copyCOPY

The toggleNumber function manages the selection state of numbers within an array. It adds a number to the array if it’s not already present or removes it if it is. This is particularly useful in scenarios like multi-select lists or checkboxes where users can select or deselect items.