draggable-react-hook v1.0.4
Draggable React Hook
A custom React hook for creating draggable components.
Installation
Install the package using npm:
npm install draggable-react-hookor using Yarn:
yarn add draggable-react-hookUsage
Import the useDraggable hook from the package:
import useDraggable from "draggable-react-hook";Use the useDraggable hook in your component:
function DraggableComponent() {
const draggableProps = useDraggable();
return <div {...draggableProps}>Drag me</div>;
}The useDraggable hook returns a set of props that need to be spread onto the element you want to make draggable. These props include event handlers and styles for drag functionality.
Example
Here's a simple example of how to use the useDraggable hook:
import React from "react";
import useDraggable from "draggable-react-hook";
function DraggableComponent() {
const draggableProps = useDraggable();
return (
<div {...draggableProps}>
<h1>Draggable Component</h1>
<p>Drag me around!</p>
</div>
);
}
export default DraggableComponent;In the example above, the DraggableComponent will be draggable within its parent container.
To enable independent dragging for each component, you need to create separate draggableProps objects for each component.
i.e :
import React from "react";
import useDraggable from "draggable-react-hook";
const DragMe = () => {
const draggableProps1 = useDraggable();
const draggableProps2 = useDraggable();
return (
<>
<div className="drag-green " {...draggableProps1}>
<h1>Green Component</h1>
<p>Drag me around!</p>
</div>
<div className="drag-red" {...draggableProps2}>
<h1>Red Component</h1>
<p>Drag me around!</p>
</div>
</>
);
};
export default DragMe;API
The useDraggable hook does not accept any parameters and returns an object with the following properties:
onMouseDown: Event handler for the mousedown event.onMouseMove: Event handler for the mousemove event.onMouseUp: Event handler for the mouseup event.onTouchStart: Event handler for the touchstart event.onTouchMove: Event handler for the touchmove event.onTouchEnd: Event handler for the touchend event.style: An object containing inline styles for the draggable element. This includes thetransformproperty for positioning and theopacityproperty for visual feedback during dragging.
Author
4SAMU-Github
Tips
Double tap+hold and Move
Left Click+hold and Move
Touch and move
challenge π₯
Create a game using the package, Happy Hackingπ¨π»βπ»π©βπ»!!!
Enjoy Using draggable-react-hook package! π₯³π₯³π₯³