Ibra
Ibra

Reputation: 1072

react-draggable save position of mapped objects in React Functional Component

How can I have each draggable object have it's own state. For example if I drag one of the objects all other mapped objects share the same state and so follow each other. How can I have each one be separate.

// State
const [x, setX]= useState(0)
const [y, setY]= useState(0)

const handleStop = (event, dragElement) => {
    setX(dragElement.x)
    setY(dragElement.y)
  };

{ numberofGraphs.map( (si, k) => (
       
       <>
       <Draggable
        onStop={handleStop} 
        position={{x: x, y:y}}
       > 
       
       <div className="resizablebox"> 
       
       </div>
       </Draggable>
     
       </>

Upvotes: 0

Views: 5728

Answers (1)

Shyam
Shyam

Reputation: 5497

Create a new custom component which render your Draggable and move the state inside it . So that each Draggable will now have its own state instead of one common state for all .

CustomComponent

const [x, setX]= useState(0)
const [y, setY]= useState(0)

const handleStop = (event, dragElement) => {
    setX(dragElement.x)
    setY(dragElement.y)
  };

return (
       <>
       <Draggable
        onStop={handleStop} 
        position={{x: x, y:y}}
       > 
       
       <div className="resizablebox"> 
       
       </div>
       </Draggable>
      )

Now in the map you can just render

numberofGraphs.map( (si, k) => (
      <CustomComponent />
)

The advantage of this is that when you drag something in CustomComponent1 only that will re-render because it has its own atomic state .

Upvotes: 4

Related Questions