Absolutely! Let's add some emojis and improve the visual appeal with a simple diagram.
🚀 Enhancing Drag-and-Drop in React-Select
Today, we'll embark on a journey to amplify the drag-and-drop experience in the react-select
library. 🎉 To begin, let's gear up with the essential Higher Order Components (HOC) from both react-select
and react-sortable-hoc
.
import Select, { components } from "react-select";
import { SortableContainer, SortableElement } from "react-sortable-hoc";
To facilitate the drag-and-drop events, we'll wield a moveable array and a customized MultiValue
function. 🛠️
// Function for drag and drop
function arrayMove(array, from, to) {
array = array.slice();
array.splice(to < 0 ? array.length + to : to, 0, array.splice(from, 1)[0]);
return array;
}
// Crafting a draggable MultiValue component
const SortableMultiValue = SortableElement((props) => {
const onMouseDown = (e) => {
e.preventDefault();
e.stopPropagation();
};
const innerProps = { onMouseDown };
return <components.MultiValue {...props} innerProps={innerProps} />;
});
// Assembling a sortable Select component
const SortableSelect = SortableContainer(Select);
Now, let's infuse life into our drag-and-drop adventure by using the onChange
and onSortEnd
functions to dance with selection and reordering.
// Example with mandatory skills 🌟
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));
};
Lastly, let's bring all the props together in our stage, the SortableSelect
component. It eagerly accepts all the props from react-select
and adds a touch of magic with draggable MultiValues. ✨
<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}
/>
With this, we aim to not only enhance functionality but also add a dash of fun and excitement to the reading experience! 🚀📚
Top comments (0)