DEV Community

Tejendra Singh Rajawat
Tejendra Singh Rajawat

Posted on • Updated on

๐ŸŽจ Mastering Drag-and-Drop in React-Select: A Visual Guide ๐Ÿš€

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";
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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));
};
Enter fullscreen mode Exit fullscreen mode

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}
/>
Enter fullscreen mode Exit fullscreen mode

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)