Skip to content

DraggableGrid not working when element's array change length #48

Description

@thorvald-man
import React, {useEffect} from 'react'

import {DndProvider, Draggable, DraggableGrid} from '@mgcrea/react-native-dnd'
import {Text, SafeAreaView, StyleSheet} from 'react-native'

const GRID_SIZE = 3
const items = ['1', '2', '3', '4', '5', '6', '7', '8', '9']

export default function App() {
  const [data, setData] = React.useState([])
  const onOrderChange = order => {
    const updatedItems = data.sort((a, b) => {
      return order.indexOf(a.id) - order.indexOf(b.id)
    })
    setData(updatedItems)
  }
  useEffect(() => {
    setInterval(() => {
      setData(pr => [
        ...pr,
        {
          id: `${pr.length}-${items[pr.length]}`,
          value: items[pr.length],
        },
      ])
    }, 2000)
  }, [])
  return (
    <SafeAreaView style={styles.container}>
      <DndProvider>
        <DraggableGrid
          direction="row"
          size={GRID_SIZE}
          style={styles.grid}
          onOrderChange={onOrderChange}>
          {data.map(item => (
            <Draggable key={item.id} id={item.id} style={styles.draggable}>
              <Text style={styles.text}>{item.value}</Text>
            </Draggable>
          ))}
        </DraggableGrid>
      </DndProvider>
    </SafeAreaView>
  )
}
const LETTER_WIDTH = 100
const LETTER_HEIGHT = 100
const LETTER_GAP = 10
const styles = StyleSheet.create({
  container: {
    flexGrow: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  grid: {
    backgroundColor: 'rgba(0,0,0,0.1)',
    alignItems: 'center',
    justifyContent: 'flex-start',
    width: LETTER_WIDTH * GRID_SIZE + LETTER_GAP * (GRID_SIZE - 1),
    gap: LETTER_GAP,
    borderRadius: 32,
  },
  draggable: {
    backgroundColor: 'seagreen',
    width: LETTER_WIDTH,
    height: LETTER_HEIGHT,
    borderColor: 'rgba(0,0,0,0.2)',
    borderWidth: 1,
    overflow: 'hidden',
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 32,
  },
  text: {
    color: 'white',
    fontWeight: 'bold',
    fontSize: 32,
  },
})

Describe the bug
When you change the number of elements in the array, the binding to the positions flies and everything breaks.

Platform & Dependencies

{
"expo": "~53.0.10",
"@mgcrea/react-native-dnd": "~2.5.3",
"react-native-gesture-handler": "~2.25.0",
"react-native-reanimated": "~3.18.0",
}
2025-06-12.14.16.34.mp4

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions