skip to Main Content

I want to keep the dragged object on the top of other objects.

So,

I have css basic.module.css

.dragging-shelf {
  z-index:100;
}

then in function

import styles from "../css/basic.module.css";

const [isDragging, setIsDragging] = useState(false)
const handleStart = (e,data) =>{
    console.log("drag before:",data.node.classList);
    data.node.classList.add("dragging-shelf");
    console.log("drag after:",data.node.classList); 
    setIsDragging(true);
}
const handleStop = (e,data) =>{
    console.log("drag handle stop e:",e);
    console.log("drag handle stop data::",data);
    data.node.classList.remove("dragging-shelf");
    setIsDragging(false);
}

 return <Draggable onStart={handleStart} onDrag={handleDrag} onStop={handleStop}>   
         <div className='handle'>
          <MyObj></MyObj></div>
         </Draggable>

I can confirm dragging-shelf is added to data.node.classList with console.log.

However this is not reflected on browser.

My Dragged obj is behind another objs.

2

Answers


  1. The imperatively toggled css class is probably removed when the call to setIsDragging causes a re-render. Set the class declaratively instead:

    ...
    return (
      <Draggable className={isDragging ? 'dragging-shelf' : ''} ...>   
        ...
      </Draggable>
    )
    
    Login or Signup to reply.
  2. In ReactJS, whenever you want to make a list of classes dynamically, you can use libraries such as clsx or classnames.

    As Vayne mentioned in the comment above, in your case, you can create a boolean useState to store your dragging status, then pass it in clsx or classnames as a condition. As a result of re-rendering, your component always has expected classes.

    Example:

    import clsx from 'clsx';
    import styles from '../css/basic.module.css';
    
    function DragComponnets() {
      const [isDragging, setIsDragging] = useState(false)
    
      const handleStart = (e,data) => {
        setIsDragging(true);
      }
      const handleStop = (e,data) => {
        setIsDragging(false);
      }
    
      return (
        <Draggable onStart={handleStart} onDrag={handleDrag} onStop={handleStop}>   
          <div className={clsx('handle', {
            'dragging-shelf': isDragging
          )}>
              <MyObj></MyObj>
          </div>
        </Draggable>
      )
    }
    

    I hope this can solve your problem.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search