D
D
dotnetlooper2021-12-28 13:46:05
React
dotnetlooper, 2021-12-28 13:46:05

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));
....


The logic of the page where the list of lists is located:
function NotePage() {   
    const moveNote = useCallback((dragIndex, hoverIndex) => {
        const dragNote = notes[dragIndex];
        setNotes(update(notes, {
            $splice: [
                [dragIndex, 1],
                [hoverIndex, 0, dragNote],
            ],
        }));
    }, [notes]);


Where do I need to make changes (put) in the component itself or on the page where they are listed? And how to pass this position of the element?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question