Alexander
Alexander

Reputation: 167

React native: Set the coordinates for each item in array

I try get the coordinates for each of my Draggaable Items.
Right now I get the coordinates but I only get one value for all the items, but I want a value for each item.

This is my data

  const data = [
    {
      name: " ",
      X: 680,
      Y: 80,
      newposX: positionX,
      newposY: positionY,
    },
    {
      name: " ",
      X: 550 ,
      Y: 80,
      newposX: positionX,
      newposY: positionY,
    },
    {
      name: " ",
      X: 550 ,
      Y: 80,
      newposX: positionX,
      newposY: positionY,
    },
  ];

Here I print out the data in a draggable element

            {data.map((item, key) => (
             <Draggable
                x={item.X}
                y={item.Y}
                renderColor="blue"
                renderSize={50}
                isCircle
                textcolor="#000000"
                renderText={item.name}
                onDragRelease={e => {
                  setPositionY(e.nativeEvent.pageY);
                  setPositionX(e.nativeEvent.pageX);
                }}
                />
              ))}

On the "onDragRelease" I set my position by get the coordinates. But here I want too set the postion for each items. but I don't get i works. Do anyone have a clue of what I schould do?

Upvotes: 1

Views: 313

Answers (1)

ajthyng
ajthyng

Reputation: 1275

In your data.map function you are declaring the index of item as variable key. You can use this to have a new setItemPosition update your data array with new positions.

const setItemPosition = (key, x, y) => {
  const updatedData = [...data]
  const item = data[key];
  item.X = x
  item.Y = y
  const updatedData[key] = item
  
  setData(updatedData) // <-- This is your "setState" function for the data array.
}

// Use it in your draggable like this:

            {data.map((item, key) => (
             <Draggable
                x={item.X}
                y={item.Y}
                renderColor="blue"
                renderSize={50}
                isCircle
                textcolor="#000000"
                renderText={item.name}
                onDragRelease={e => {
                  setItemPosition(key, e.nativeEvent.pageX, e.nativeEvent.pageY);
                }}
                />
              ))}

Upvotes: 1

Related Questions