0

I'm creating a simple quiz which has 4 droppable areas and 4 draggable items and idea behind this quiz to move all items into correct order or just to correct droppable zone.

enter image description here

Now everything is working - items are swiping (when I move f.e. item 1 to droppable 3 then droppable 1 has item 3 and droppable 3 has item 1)

enter image description here

The problem is draggables don't have any transition on drag end. I've implemented transition in following way:

draggable/index.tsx:

import { useDraggable } from '@dnd-kit/core';
import { CSS } from '@dnd-kit/utilities';
import clsx from 'clsx';
import React, { ReactNode } from 'react';

import s from './draggable.module.scss';

type TProps = {
   children: ReactNode;
   id: string;
};

export const Draggable = ({ id, children }: TProps) => {
   const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({
      id,
   });
   const style = {
      ...{ transition: 'transform 250ms ease' },
      ...(transform ? { transform: CSS.Translate.toString(transform) } : {}),
      ...(isDragging ? { transition: 'none' } : {}),
   };

   return (
      <button
         ref={setNodeRef}
         className={clsx(s.wrapper, isDragging && s.dragging)}
         style={style}
         {...listeners}
         {...attributes}
      >
         {children}
      </button>
   );
};

LINKS

CODE

github: /src/app/page.tsx

github: /src/components/dnd/draggable/index.tsx

github: /src/components/dnd/droppable/index.tsx

DEPLOYED EXAMPLE

vercel: Try it yourself

1 Answer 1

0

use a state and useEffect to track drag ending.

const { attributes, listeners, setNodeRef, transform, isDragging, active } 
= useDraggable({id});

const [style, setStyle] = useState({});


useEffect(() => {

  if (!isDragging && active) {

     setStyle((prevStyle) => ({

        ...prevStyle,

        transition: 'transform 250ms ease',

        transform: CSS.Translate.toString(transform),

     }));

  }

  if (!active) {

     setStyle({

        transition: 'transform 250ms ease',

     });

  }

}, [isDragging, transform, active]);

when the current drag has just ended, active is true and isDragging is false so the transition is applied to the transform style.

on the hand When active is false the transition resets.

1
  • Unfortunately with your approach transition disappeared completely
    – Lvasche
    Commented Jul 2 at 6:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.