react-grid-layout / react-draggable

React draggable component
MIT License
9.01k stars 1.02k forks source link

I just want my Element that can only be moved to viewport,because my element is position of fixed。but I set bounds="body" and cannot work,is still can move in the direction of down while out of viewpoint #714

Open hututuhu opened 1 year ago

hututuhu commented 1 year ago
<Draggable
    disabled={!isDraggable}
    handle=".br-modal__header"
    defaultClassNameDragged="br-modal__default-drag"
    positionOffset={unblock ? { x: '-50%', y: '-50%' } : undefined}
    cancel={resizable ? '.react-resizable-handle' : undefined}
    bounds="body"
  >
    {resizeElement}
</Draggable>

image

tinywaves commented 1 year ago

Yes, I also encountered this problem. Do you have the solution now? Thank you. @hututuhu

hardik79 commented 1 year ago

Hello @tinyRipple and @hututuhu , I have a solution to your problem. Please add bounds={bounds} into the Draggable and ref={dragRef} into the main draggable div like Screenshot_1

hardik79 commented 1 year ago

Check https://github.com/hardik79/react-draggable/blob/main/src/App.js solution example for your problem.

hututuhu commented 1 year ago

Yes, I also encountered this problem. Do you have the solution now? Thank you. @hututuhu

I solve this problem by using onStop and position. image

image

YuLingCheng commented 7 months ago

Check https://github.com/hardik79/react-draggable/blob/main/src/App.js solution example for your problem.

Setting the computed bounds works well, thanks for the tip 👍 I think we can manage without a useEffect and rely on the onStart prop to recompute the bounds whenever the users want to start dragging. I just used this strategy to solve similar issue to limit the bounds of a draggable Mui modal.

function App() {
  const [bounds, setBounds] = useState({});
  const contentRef = useRef(null);

  function updateBounds() {
    if (contentRef.current !== null) {
      setBounds({
        left: ..., 
        top: ...,
        right: ...,
        bottom: ..., // Whatever computation works in your case based on contentRef.current
      });
    }

  return (
    <Draggable bounds={bounds} onStart={updateBounds}>
      <YourComponent ref={contentRef} />
    </Draggable>
  );
}