Answer the question
In order to leave comments, you need to log in
How to change the position of an element in a list?
You need to change the order of the records using drag and drop. I used react-dnd for this. Everything is fine, but the problem is that these changes occur on the client side. And I need to change positions on the server as well. Where and how can I transfer positions? For example, each entry has an attribute => position.
Component logic:
function Note({ id, index, date, title, description, thumbnail, moveNote }) {
const ref = useRef(null);
const [{ handlerId }, drop] = useDrop({
accept: 'note',
collect(monitor) {
return {
handlerId: monitor.getHandlerId()
}
},
hover(item, monitor) {
if (!ref.current) {
return;
}
const dragIndex = item.index;
const hoverIndex = index;
if (dragIndex === hoverIndex) {
return;
}
const hoverBoundingRect = ref.current?.getBoundingClientRect();
const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
const clientOffset = monitor.getClientOffset();
const hoverClientY = clientOffset.y - hoverBoundingRect.top;
if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
return;
}
if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
return;
}
moveNote(dragIndex, hoverIndex);
item.index = hoverIndex;
},
});
const [{ isDragging }, drag] = useDrag({
type: 'note',
item: () => {
return { id, index };
},
collect: monitor => ({
isDragging: monitor.isDragging(),
}),
});
const opacity = isDragging ? 0 : 1;
drag(drop(ref));
....
function NotePage() {
const moveNote = useCallback((dragIndex, hoverIndex) => {
const dragNote = notes[dragIndex];
setNotes(update(notes, {
$splice: [
[dragIndex, 1],
[hoverIndex, 0, dragNote],
],
}));
}, [notes]);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question