Drag and Drop List Sortable
by Chill_bi
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-is/17.0.1/umd/react-is.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/styled-components.min.js"></script>
<div id='root'></div>
SCSS
* {
padding: 0;
margin: 0;
color: white;
}
React
const _SocialNetworks = [
{title: "Twitter", color: "white", backgroundColor: "Red"},
{title: "Facebook", color: "black", backgroundColor: "Orange"},
{title: "Line", color: "black", backgroundColor: "Yellow"},
{title: "Instagram", color: "white", backgroundColor: "Green"},
{title: "Telegram", color: "white", backgroundColor: "Blue"},
{title: "KaKao", color: "white", backgroundColor: "DarkBlue"},
{title: "LinkedIn", color: "white", backgroundColor: "Purple"},
]
const _initGrabData = {
target: null,
position: null,
move_up: [],
move_down: [],
updateList: []
}
const App = () => {
const [ lists, setLists ] = React.useState(_SocialNetworks);
const [ grab, setGrab ] = React.useState(_initGrabData);
const [ isDrag, setIsDrag ] = React.useState(false);
React.useEffect(() => {}, [grab]);
const _onDragOver = e => {
e.preventDefault();
}
const _onDragStart = e => {
setIsDrag(true);
setGrab({
...grab,
target: e.target,
position: Number(e.target.dataset.position),
updateList: [ ...lists ]
});
e.target.classList.add("grabbing");
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("text/html", e.target);
}
const _onDragEnd = e => {
setIsDrag(false);
e.target.classList.remove("grabbing");
e.dataTransfer.dropEffect = "move";
setLists([ ...grab.updateList ]);
setGrab({
target: null,
move_up: [],
move_down: [],
updateList: []
});
e.target.style.visibility = "visible";
}
const _onDragEnter = e => {
let grabPosition = Number(grab.target.dataset.position);
let listPosition = grab.position;
let targetPosition = Number(e.target.dataset.position);
let move_up = [ ...grab.move_up ];
let move_down...