Live working example: https://react-3gte8y.stackblitz.io/
code : https://stackblitz.com/edit/react-3gte8y?file=src/App.js
First keep your options array contain only numbers:
const options = [1, 2, 3, 4, 5];
then in your onChange handler function check if the selected value already exist in the nums state, if not exist add it, else remove it
how to that? easy get the index of the value using indexOf
method, if it return -1 means number not exist in num
array, else indexOf will return the actual index of your chosen number:
const handleArrChange = ({ target }) => {
setNum((prev) => {
//get index of actual target.value
const index = prev.indexOf(target.value);
/*if index === -1 means not exist in array will return the prev
state and appending new chosen value*/
if (index === -1) {
return [...prev, target.value];
}
/* else (value exist) use splice to remove the chosen value from
the array */
prev.splice(index, 1);
/* don't use return prev, React will not detect changes in your
state and will not re render it */
return [...prev];
});
};
prev is the previous state, it hold actual state before making any change to the num state.
Now make some change to your JSX, first don't forget keys, and make sure to set default select value to select
the disabled option:
<select onChange={handleArrChange} value={"select"}>
<option disabled>select</option>
{options.map((option) => (
<option key={option}>{option}</option>
))}
</select>
and
{nums.map((num) => (
<p key={num}>{num}</p>
))}
Now you need one thing is to select All and deselect all
first add all to your options:
<select onChange={handleArrChange} value={"select"}>
<option disabled>select</option>
<option>All</option>
{options.map((option) => (
<option key={option}>{option}</option>
))}
</select>
then in the onChange function handler check if is All is checked:
if(target.value === "All"){
if(nums.length > 0 ){
setNum([])
}else{
setNum(options)
}
return
}
this code must be first thing you do when select value changes, add it to the top of your onChange function:
here is the full working code:
import React, { useState } from "react";
const options = [1, 2, 3, 4, 5];
export default function App() {
const [nums, setNum] = useState([]);
const handleArrChange = ({ target }) => {
if(target.value === "All"){
if(nums.length > 0 ){
setNum([])
}else{
setNum(options)
}
return
}
setNum((prev) => {
const index = prev.indexOf(target.value);
if (index === -1) {
return [...prev, target.value];
}
prev.splice(index, 1);
return [...prev];
});
};
return (
<div className="App">
<select onChange={handleArrChange} value={"select"}>
<option disabled>select</option>
<option>All</option>
{options.map((option) => (
<option key={option}>{option}</option>
))}
</select>
{nums.map((num) => (
<p key={num}>{num}</p>
))}
</div>
);
}