Today we are discussing how to use drag and drop in react-select library.
For that we need to use High order component of react-select and react-sortable-hoc.
import Select, { components } from "react-select";
import { SortableContainer, SortableElement } from "react-sortable-hoc";
Now we need moveable array and multiValue function to control drag and drop events.
// drag and drop use
function arrayMove(array, from, to) {
array = array.slice();
array.splice(to < 0 ? array.length + to : to, 0, array.splice(from, 1)[0]);
return array;
}
const SortableMultiValue = SortableElement((props) => {
const onMouseDown = (e) => {
e.preventDefault();
e.stopPropagation();
};
const innerProps = { onMouseDown };
return <components.MultiValue {...props} innerProps={innerProps} />;
});
const SortableSelect = SortableContainer(Select);
// drag and drop use
Here we will use onChange and onsortEnd function to set value and onChange value when selected and drag and drop.
// drag and drop use mand
const [selectedMand, setSelectedMand] = React.useState([
...getMandatorySkillOption,
]);
const onChangeMand = (selectedOptions) => setSelectedMand(selectedOptions);
const onSortEndMan = ({ oldIndex, newIndex }) => {
const newValue = arrayMove(selectedMand, oldIndex, newIndex);
setSelectedMand(newValue);
console.log(
"Values sorted:",
newValue.map((i) => i.value)
);
};
// end drag and drop use mand
Finally we will use all props in sortableSelect which accepts all props or react-select too.
<SortableSelect
axis="xy"
styles={customStyles}
classNamePrefix={"create_position"}
onSortEnd={onSortEndMan}
distance={4}
getHelperDimensions={({ node }) => node.getBoundingClientRect()}
isMulti
options={getMandatorySkillOption}
value={selectedMand}
onChange={onChangeMand}
components={{
MultiValue: SortableMultiValue,
}}
defaultValue={formData?.mandatorySkill?.map((i) => ({
value: i.id,
label: i.mandatorySkillName,
}))}
closeMenuOnSelect={false}
/>
Top comments (0)