I want to make a multi filter so that user can remove any of the item until items length is one. I want to add isFixed = true in the object dynamically when user remove 2 out of 3 items for this below example.
import React, { useState } from 'react';
import Select from 'react-select';
const options = [
{ value: 'apple', label: 'Apple' },
{ value: 'orange', label: 'Orange' },
{ value: 'grape', label: 'Grape' },
];
const orderOptions = (values) =>
values && values.filter((v) => v.isFixed).concat(values.filter((v) => !v.isFixed));
export default function TestSelect() {
const [value, setValue] = useState(orderOptions([...options]));
console.log('value', value);
const onChange = (value, { action, removedValue }) => {
switch (action) {
case 'remove-value':
case 'pop-value':
if (removedValue.isFixed) {
return;
}
break;
case 'clear':
value = options.filter((v) => v.isFixed);
break;
default:
break;
}
value = orderOptions(value);
setValue(value);
};
return (
<div>
<Select
value={value}
isMulti
isClearable={value && value.some((v) => !v.isFixed)}
name="fruit"
classNamePrefix="select"
onChange={onChange}
options={options}
defaultValue={options}
/>
</div>
);
}
You just have to check if there's only one element remaining in the values array within the switch-case. To do so, just add two lines:
...
const onChange = (value, { action, removedValue }) => {
switch (action) {
case "remove-value":
case "pop-value":
if (removedValue.isFixed) return;
if (value.length === 1) value[0].isFixed = true; // <-- add the isFixed element
break;
case "clear":
value = options.filter((v) => v.isFixed);
break;
default:
value.forEach(x => x.isFixed = false) // <-- remove the isFixed element
break;
}
value = orderOptions(value);
setValue(value);
};
...
Remember to add the styles part to make it more visual. As you can see here.