### Example Drag Start Animation Styles
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/api-reference/Block.md
Illustrates the animation styles applied to a Block component when it is being dragged.
```typescript
{
zIndex: 3,
transform: [{ scale: dragStartAnimatedValue }],
shadowColor: '#000000',
shadowOpacity: 0.2,
shadowRadius: 6,
shadowOffset: { width: 1, height: 1 }
}
```
--------------------------------
### Making Draggable Grid Responsive with useWindowDimensions
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/troubleshooting.md
This example demonstrates how to make the grid responsive by dynamically setting the number of columns based on the screen width. It uses the `useWindowDimensions` hook to get the current width.
```typescript
import { Dimensions, useWindowDimensions } from 'react-native'
export function ResponsiveGrid() {
const { width } = useWindowDimensions()
const numColumns = width > 600 ? 4 : 2
return (
)
}
```
--------------------------------
### Custom Drag Start Animation
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/README.md
Implement a custom animation when dragging starts by providing a `dragStartAnimation` prop. This example uses `Animated.timing` to scale the item.
```javascript
render() {
return (
);
}
private onDragStart = () => {
this.state.animatedValue.setValue(1);
Animated.timing(this.state.animatedValue, {
toValue:3,
duration:400,
}).start();
}
```
--------------------------------
### Using Draggable Grid with React Native Web
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/troubleshooting.md
This example shows the basic setup for using `DraggableGrid` in a web application with `react-native-web`. Ensure `react-native-web` is installed and configured in your project.
```typescript
// App.web.tsx
import { DraggableGrid } from 'react-native-draggable-grid'
export default function App() {
return
}
```
--------------------------------
### Install react-native-draggable-grid
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/integration-guide.md
Install the library using npm or yarn. Ensure you meet the React and React Native version requirements.
```bash
npm install react-native-draggable-grid
# or
yarn add react-native-draggable-grid
```
--------------------------------
### Install react-native-draggable-grid
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/README.md
Install the library using npm. This command adds the package as a dependency to your project.
```bash
npm install react-native-draggable-grid --save
```
--------------------------------
### TypeScript Code Example
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/README.md
This snippet demonstrates the use of TypeScript for defining code examples within the documentation. It indicates recommended practices.
```typescript
// Shows actual TypeScript code
// ✓ Recommended
// ✗ Anti-pattern
```
--------------------------------
### Basic Draggable Grid Usage
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/api-reference/DraggableGrid.md
Demonstrates the fundamental setup of the DraggableGrid component with a simple array of items and basic styling.
```typescript
import React, { useState } from 'react'
import { View, Text, StyleSheet } from 'react-native'
import { DraggableGrid } from 'react-native-draggable-grid'
interface Item {
key: string
name: string
}
export function BasicGrid() {
const [items, setItems] = useState([
{ key: '1', name: 'Item 1' },
{ key: '2', name: 'Item 2' },
{ key: '3', name: 'Item 3' },
])
return (
(
{item.name}
)}
onDragRelease={(sortedData) => {
setItems(sortedData)
}}
/>
)
}
const styles = StyleSheet.create({
itemContainer: {
flex: 1,
backgroundColor: '#e0e0e0',
justifyContent: 'center',
alignItems: 'center',
},
})
```
--------------------------------
### Example Usage: findKey
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/api-reference/utilities.md
Demonstrates how to use the findKey utility function to locate an item's key based on a property value, including cases where the item is not found.
```typescript
const orderMap = {
'item1': { order: 0 },
'item2': { order: 1 },
'item3': { order: 2 },
}
// Find the key of the item with order 1
const key = findKey(orderMap, item => item.order === 1)
console.log(key) // 'item2'
// Find the first key (returns first found)
const firstKey = findKey(orderMap, () => true)
console.log(firstKey) // 'item1'
// Returns undefined if not found
const notFound = findKey(orderMap, item => item.order === 99)
console.log(notFound) // undefined
```
--------------------------------
### Custom Animated Value Drag Start Animation
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/integration-guide.md
Implement complex, dynamic drag start animations using `Animated.Value` and `Animated.timing` for transformations like scaling and rotation. Requires `useNativeDriver: false` for certain properties.
```typescript
import { useRef } from 'react'
import { Animated, Easing } from 'react-native'
export function GridWithCustomAnimation() {
const scaleAnim = useRef(new Animated.Value(1)).current
const rotateAnim = useRef(new Animated.Value(0)).current
const handleDragStart = () => {
// Parallel animations
Animated.parallel([
Animated.timing(scaleAnim, {
toValue: 1.3,
duration: 300,
easing: Easing.elastic(1),
useNativeDriver: false,
}),
Animated.timing(rotateAnim, {
toValue: 1,
duration: 300,
useNativeDriver: false,
}),
]).start()
}
const handleDragRelease = (newData: Item[]) => {
// Reset animations
Animated.parallel([
Animated.timing(scaleAnim, {
toValue: 1,
duration: 200,
useNativeDriver: false,
}),
Animated.timing(rotateAnim, {
toValue: 0,
duration: 200,
useNativeDriver: false,
}),
]).start()
setItems(newData)
}
return (
}
/>
)
}
```
--------------------------------
### Custom Static Drag Start Animation
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/integration-guide.md
Apply custom static styles like opacity and background color to the item during drag start using the `dragStartAnimation` prop.
```typescript
}
/>
```
--------------------------------
### Handling Drag Events in Draggable Grid
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/api-reference/DraggableGrid.md
Provides examples of various event handlers for tracking item interactions, drag start, active drag, and release events.
```typescript
function GridWithEvents() {
return (
}
onItemPress={(item) => {
console.log('Item tapped:', item.key)
}}
onDragStart={(item) => {
console.log('Started dragging:', item.key)
}}
onDragItemActive={(item) => {
console.log('Item activated:', item.key)
}}
onDragging={(gestureState) => {
console.log('Current drag position:', {
x: gestureState.moveX,
y: gestureState.moveY,
})
}}
onResetSort={(newData) => {
console.log('Item swapped, new order:', newData.map(i => i.key))
}}
onDragRelease={(newData) => {
console.log('Drag completed, final order:', newData.map(i => i.key))
setItems(newData)
}}
/>
)
}
```
--------------------------------
### Basic Simple Grid Setup
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/integration-guide.md
Demonstrates setting up a basic draggable grid with a specified number of columns and custom item rendering. The onDragRelease callback is used to update the component's state with the new item order.
```typescript
import React, { useState } from 'react'
import { View, StyleSheet } from 'react-native'
import { DraggableGrid } from 'react-native-draggable-grid'
interface Item {
key: string
name: string
}
export function SimpleGrid() {
const [items, setItems] = useState([
{ key: '1', name: 'Item 1' },
{ key: '2', name: 'Item 2' },
{ key: '3', name: 'Item 3' },
{ key: '4', name: 'Item 4' },
])
return (
(
{item.name}
)}
onDragRelease={(newData) => {
setItems(newData)
}}
/>
)
}
const styles = StyleSheet.create({
item: {
flex: 1,
backgroundColor: '#e0e0e0',
justifyContent: 'center',
alignItems: 'center',
borderRadius: 8,
},
})
```
--------------------------------
### TypeScript Usage Example
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/module-exports.md
Demonstrates how to import and use the DraggableGrid component with TypeScript, including defining item types and props. It shows the basic setup for integrating the component into a React Native application.
```typescript
import { DraggableGrid, type IDraggableGridProps } from 'react-native-draggable-grid'
interface PhotoItem {
key: string
uri: string
}
type PhotoGridProps = IDraggableGridProps
const MyGrid: React.FC = (props) => {
return
}
```
--------------------------------
### RTL Adjustments for Positioning and Styling
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/internals.md
Provides examples of how to adjust positioning and styling logic to support Right-to-Left (RTL) layouts using `I18nManager.isRTL`.
```typescript
// In drag positioning
const x = activeOrigin.x + (I18nManager.isRTL ? x0 : -x0)
// In movement tracking
const moveX = I18nManager.isRTL ? -moveXOriginal : moveXOriginal
// In block styling (web-specific)
right: I18nManager.isRTL && Platform.OS === 'web' ? left : undefined
left: I18nManager.isRTL && Platform.OS === 'web' ? undefined : left
```
--------------------------------
### Package Import Paths: Default and Named Imports
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/module-exports.md
Demonstrates how to import the DraggableGrid component and its types using default and named import syntax from the installed package.
```typescript
// Default import
import DraggableGrid from 'react-native-draggable-grid'
// Named imports
import { DraggableGrid, type IDraggableGridProps } from 'react-native-draggable-grid'
// Type imports (TypeScript)
import type { IDraggableGridProps } from 'react-native-draggable-grid'
```
--------------------------------
### Example of getSortData Output
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/internals.md
Illustrates the output of the `getSortData` function, showing how items are placed into the resulting array according to their order index.
```typescript
items = [
{ key: 'a', itemData: {name: 'A'} },
{ key: 'b', itemData: {name: 'B'} },
{ key: 'c', itemData: {name: 'C'} }
]
orderMap = {
'a': { order: 2 },
'b': { order: 0 },
'c': { order: 1 }
}
getSortData() returns:
[
{name: 'B'}, // order 0
{name: 'C'}, // order 1
{name: 'A'} // order 2
]
```
--------------------------------
### Custom Item Type Extension Example
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/types.md
Illustrates how to extend the base IBaseItemType to create a custom data structure for grid items. This example shows adding specific properties like 'title' and 'thumbnail', and demonstrates setting disabled flags.
```typescript
interface CustomItem extends IBaseItemType {
key: string
title: string
thumbnail: string
metadata?: Record
disabledDrag?: boolean
disabledReSorted?: boolean
}
const items: CustomItem[] = [
{
key: 'item1',
title: 'Photo 1',
thumbnail: 'https://example.com/photo1.jpg',
},
{
key: 'item2',
title: 'Header',
thumbnail: '',
disabledReSorted: true,
},
]
```
--------------------------------
### Example Base Layout Styles
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/api-reference/Block.md
Shows the base layout styles applied to a Block component when rendered by DraggableGrid.
```typescript
{
justifyContent: 'center',
alignItems: 'center',
width: blockWidth,
height: blockHeight,
position: 'absolute',
top: currentPosition.getLayout().top,
left: currentPosition.getLayout().left,
}
```
--------------------------------
### Tracking Dragged Item with onDragStart
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/troubleshooting.md
This example shows how to track the currently dragged item using the `onDragStart` callback. The dragged item's state is updated and then cleared on drag release.
```typescript
const [draggedItem, setDraggedItem] = useState(null)
{
setDraggedItem(item) // Track dragged item
}}
onDragRelease={(newData) => {
setItems(newData)
setDraggedItem(null) // Clear
}}
renderItem={(item) => (
{item.name}
)}
/>
```
--------------------------------
### Customizing Drag Start Animation with Animated.spring
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/troubleshooting.md
This snippet shows how to customize the drag start animation using the `dragStartAnimation` prop with `Animated.spring`. It requires importing `Animated` and using `useRef` for the animation value.
```typescript
const scale = useRef(new Animated.Value(1)).current
const handleDragStart = () => {
Animated.spring(scale, {
toValue: 1.3,
useNativeDriver: false,
}).start()
}
```
--------------------------------
### Items Array Example
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/internals.md
Shows the structure of the 'items' array, where each element contains an item's key, data, and its animated position values.
```typescript
items = [
{ key: 'item1', itemData: {...}, currentPosition: AnimatedValueXY(...) },
{ key: 'item2', itemData: {...}, currentPosition: AnimatedValueXY(...) },
...
]
```
--------------------------------
### Accessibility Example for Block Children
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/api-reference/Block.md
Provides an example of how to add accessibility props to a child component rendered within a Block. This ensures proper accessibility labels and roles for interactive elements.
```typescript
{item.content}
```
--------------------------------
### Draggable Grid with Custom Item Height and Animations
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/api-reference/DraggableGrid.md
Shows how to customize item height and implement drag start animations using Animated API for a more interactive user experience.
```typescript
import React, { useState } from 'react'
import { Animated, Easing } from 'react-native'
import { DraggableGrid } from 'react-native-draggable-grid'
export function CustomAnimationGrid() {
const [scaleAnim] = useState(new Animated.Value(1))
const handleDragStart = () => {
Animated.timing(scaleAnim, {
toValue: 1.2,
duration: 200,
easing: Easing.ease,
useNativeDriver: false,
}).start()
}
return (
}
dragStartAnimation={{
transform: [{ scale: scaleAnim }],
opacity: 0.8,
}}
onDragStart={handleDragStart}
onDragRelease={(sortedData) => {
scaleAnim.setValue(1)
updateData(sortedData)
}}
delayLongPress={500}
/>
)
}
```
--------------------------------
### DraggableGrid Usage Example
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/types.md
Demonstrates how to configure and use the DraggableGrid component with custom data and event handlers. Ensure your data items conform to the IDraggableGridProps generic type.
```typescript
const gridProps: IDraggableGridProps = {
numColumns: 3,
data: myItems,
renderItem: (item, order) => ,
onDragRelease: (sortedData) => updateState(sortedData),
}
```
--------------------------------
### TypeScript Setup for Draggable Grid
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/troubleshooting.md
This snippet illustrates how to set up TypeScript for the `react-native-draggable-grid` library, including importing types and defining props for a custom item interface.
```typescript
import { DraggableGrid, type IDraggableGridProps } from 'react-native-draggable-grid'
interface Item {
key: string
title: string
}
type Props = IDraggableGridProps
const MyGrid: React.FC = (props) => {
return
}
```
--------------------------------
### Default Drag Start Animation
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/api-reference/DraggableGrid.md
This is the default animation applied when an item starts being dragged, unless a custom animation is provided via the dragStartAnimation prop.
```typescript
{
transform: [{ scale: 1.1 }],
shadowColor: '#000000',
shadowOpacity: 0.2,
shadowRadius: 6,
shadowOffset: { width: 1, height: 1 }
}
```
--------------------------------
### Example Usage: findIndex
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/api-reference/utilities.md
Demonstrates how to use the findIndex utility function to locate an element's index in an array based on a condition, including cases where no match is found.
```typescript
const items = [
{ key: 'a', name: 'Alpha' },
{ key: 'b', name: 'Beta' },
{ key: 'c', name: 'Gamma' },
]
// Find index of item with key 'b'
const idx = findIndex(items, item => item.key === 'b')
console.log(idx) // 1
// Returns -1 if not found
const notFound = findIndex(items, item => item.key === 'z')
console.log(notFound) // -1
// Find first element matching condition
const firstString = findIndex(items, item => item.name.length > 4)
console.log(firstString) // 2 (Gamma has 5 characters)
```
--------------------------------
### Extending IBaseItemType with Explicit Source Import
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/module-exports.md
Example of explicitly extending IBaseItemType by importing it directly from the source file, which requires a source import path.
```typescript
import type { DraggableGrid } from 'react-native-draggable-grid/src/draggable-grid'
interface MyItem extends IBaseItemType {
key: string
name: string
}
```
--------------------------------
### Simple Object Data Pattern
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/integration-guide.md
Example of using simple objects with a 'key' property for grid items. The DraggableGrid component is typed with the 'Photo' interface.
```typescript
interface Photo {
key: string
uri: string
width: number
height: number
}
const photos: Photo[] = [
{ key: 'photo1', uri: 'https://...', width: 300, height: 400 },
{ key: 'photo2', uri: 'https://...', width: 300, height: 400 },
]
data={photos}
renderItem={(photo) => (
)}/>
```
--------------------------------
### Configuring Accessibility for DraggableGrid Items
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/integration-guide.md
This example shows how to enhance the accessibility of DraggableGrid items by setting accessibility labels, roles, and hints. This improves usability for users with assistive technologies.
```typescript
(
)}
onDragRelease={(newData) => setItems(newData)}
/>
```
--------------------------------
### Extending IBaseItemType with Implicit Extension
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/module-exports.md
Example of how to define a custom item type that implicitly extends IBaseItemType by including the required properties.
```typescript
import { DraggableGrid } from 'react-native-draggable-grid'
interface MyItem {
key: string
name: string
// extends IBaseItemType implicitly
}
```
--------------------------------
### Persisting Grid Order with API Call on Drag Release
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/troubleshooting.md
This example shows how to persist the grid's order to a backend by making an API call within the `onDragRelease` callback. It includes optimistic updates and error handling for rollback.
```typescript
{
setItems(newData) // Optimistic update
try {
await api.updateGridOrder(
newData.map((item, order) => ({
key: item.key,
order,
}))
)
} catch (error) {
setItems(previousItems) // Rollback
showError('Failed to save')
}
}}
{...props}
/>
```
--------------------------------
### Large List Handling with FlatList
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/integration-guide.md
Use FlatList for lists exceeding 100 items to enable pagination and windowing. This example demonstrates loading items incrementally.
```typescript
export function LargeGrid() {
const [items, setItems] = useState([])
const [page, setPage] = useState(1)
useEffect(() => {
loadMoreItems(page)
}, [page])
const visibleItems = items.slice(0, page * 50)
return (
(
}
onDragRelease={(newData) => setItems(newData)}
/>
)}
onEndReached={() => setPage(p => p + 1)}
/>
)
}
```
--------------------------------
### Full Drag Lifecycle Event Handling
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/integration-guide.md
Demonstrates handling various events throughout the drag-and-drop lifecycle, from item press to drag start, dragging, reset sort, and final drag release. Useful for providing user feedback like sounds or animations.
```typescript
export function GridWithEvents() {
return (
}
// 1. User taps item (no drag)
onItemPress={(item) => {
console.log('Tapped:', item.key)
// Handle navigation, modal, etc.
}}
// 2. User holds item for delayLongPress (default 300ms)
onDragItemActive={(item) => {
console.log('Drag activated:', item.key)
// Play feedback sound, haptic feedback
}}
// 3. Gesture recognizes as drag (starts moving)
onDragStart={(item) => {
console.log('Drag started:', item.key)
// Start custom animations
}}
// 4. Dragging (continuous)
onDragging={(gestureState) => {
console.log('Current position:', {
x: gestureState.moveX,
y: gestureState.moveY,
vx: gestureState.vx,
vy: gestureState.vy,
})
}}
// 5a. Item position changes (swap)
onResetSort={(newData) => {
console.log('Swapped, new order:', newData.map(i => i.key))
// Update UI state if needed
}}
// 5b. User releases (drag ends)
onDragRelease={(newData) => {
console.log('Drag complete, final order:', newData.map(i => i.key))
// Persist to backend
saveGridOrder(newData)
}}
/>
)
}
```
--------------------------------
### Handling Item Deletion in Draggable Grid
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/troubleshooting.md
This example demonstrates how to handle item deletion by filtering the data array. The grid automatically re-renders to reflect the removal of the item.
```typescript
const deleteItem = (keyToDelete: string) => {
const newItems = items.filter(item => item.key !== keyToDelete)
setItems(newItems)
// Grid automatically updates
}
// In renderItem
renderItem={(item) => (
{item.name}
)}
```
--------------------------------
### Distinguishing onResetSort and onDragRelease Events
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/troubleshooting.md
This snippet clarifies the difference between `onResetSort` (called on every swap) and `onDragRelease` (called once on drag end). It provides example use cases for each.
```typescript
{
console.log('Item swapped') // Called multiple times
playSwapSound()
}}
onDragRelease={(newData) => {
console.log('Drag complete') // Called once
setItems(newData)
api.saveOrder(newData)
}}
/>
```
--------------------------------
### Unit Tests for DraggableGrid
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/integration-guide.md
This snippet demonstrates how to write unit tests for the DraggableGrid component using Jest. It covers rendering items and verifying their presence. Note that simulating drag events requires additional setup.
```typescript
import { render } from '@testing-library/react-native'
import { DraggableGrid } from 'react-native-draggable-grid'
describe('DraggableGrid', () => {
it('renders items correctly', () => {
const items = [
{ key: '1', name: 'Item 1' },
{ key: '2', name: 'Item 2' },
]
const { getByText } = render(
{item.name}}
/>
)
expect(getByText('Item 1')).toBeDefined()
expect(getByText('Item 2')).toBeDefined()
})
it('calls onDragRelease with new order', () => {
const onDragRelease = jest.fn()
const { getByTestId } = render(
(
{item.name}
)}
onDragRelease={onDragRelease}
/>
)
// Simulate drag would require firing PanResponder events
// This requires additional test setup
})
})
```
--------------------------------
### TypeScript Compiler Options
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/module-exports.md
Configuration for the TypeScript compiler, specifying target ECMAScript version, module system, included libraries, and JSX transformation. This setup ensures broad compatibility and proper integration with React Native.
```json
{
"compilerOptions": {
"target": "ES5",
"module": "commonjs",
"lib": ["ES2015"],
"jsx": "react-native"
}
}
```
--------------------------------
### DraggableGrid Component Usage with Custom Data Type
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/types.md
Example demonstrating how to use the DraggableGrid component with a custom data type that extends IBaseItemType. This allows for custom item properties like 'uri', 'caption', and 'author'.
```typescript
// Example with a custom data type
interface PhotoGridItem extends IBaseItemType {
key: string
uri: string
caption: string
author: string
}
numColumns={3}
data={photos}
renderItem={(item) => (
)}
/>
```
--------------------------------
### Basic Draggable Grid Usage
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/README.md
Demonstrates how to use the DraggableGrid component with basic configuration. It requires defining the number of columns, the data array, a render function for each item, and a callback for when the drag is released.
```typescript
import React, { useState } from 'react'
import { View, Text } from 'react-native'
import { DraggableGrid } from 'react-native-draggable-grid'
interface Item {
key: string
name: string
}
export function App() {
const [items, setItems] = useState([
{ key: '1', name: 'Item 1' },
{ key: '2', name: 'Item 2' },
{ key: '3', name: 'Item 3' },
])
return (
(
{item.name}
)}
onDragRelease={(newData) => {
setItems(newData)
}}
/>
)
}
```
--------------------------------
### Source Import Paths: Internal Imports
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/module-exports.md
Shows how to import components and utilities directly from the source files. This is generally not recommended for production use.
```typescript
// Direct source imports (not recommended for production)
import { DraggableGrid } from 'react-native-draggable-grid/src/draggable-grid'
import { findKey, findIndex, differenceBy } from 'react-native-draggable-grid/src/utils'
import { Block } from 'react-native-draggable-grid/src/block'
```
--------------------------------
### Package JSON Configuration
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/module-exports.md
Defines the package name, version, description, main entry point, and type definitions. It specifies the compiled JavaScript file for the 'main' field and the TypeScript source for 'types'.
```json
{
"name": "react-native-draggable-grid",
"version": "2.2.2",
"description": "A draggable grid for react native",
"main": "built/src/index.js",
"types": "src/index.ts",
"keywords": ["drag", "sortable", "grid"]
}
```
--------------------------------
### Basic Usage of DraggableGrid
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/README.md
Demonstrates how to import and use the DraggableGrid component in a React Native application. It includes setting up the data, rendering items, and handling drag release events.
```javascript
import React from 'react';
import {
View,
StyleSheet,
Text,
} from 'react-native';
import { DraggableGrid } from 'react-native-draggable-grid';
interface MyTestProps {
}
interface MyTestState {
data:{key:string, name:string}[];
}
export class MyTest extends React.Component{
constructor(props:MyTestProps) {
super(props);
this.state = {
data:[
{name:'1',key:'one'},
{name:'2',key:'two'},
{name:'3',key:'three'},
{name:'4',key:'four'},
{name:'5',key:'five'},
{name:'6',key:'six'},
{name:'7',key:'seven'},
{name:'8',key:'eight'},
{name:'9',key:'night'},
{name:'0',key:'zero'},
],
};
}
public render_item(item:{name:string, key:string}) {
return (
{item.name}
);
}
render() {
return (
{
this.setState({data});// need reset the props data sort after drag release
}}
/>
);
}
}
const styles = StyleSheet.create({
button:{
width:150,
height:100,
backgroundColor:'blue',
},
wrapper:{
paddingTop:100,
width:'100%',
height:'100%',
justifyContent:'center',
},
item:{
width:100,
height:100,
borderRadius:8,
backgroundColor:'red',
justifyContent:'center',
alignItems:'center',
},
item_text:{
fontSize:40,
color:'#FFFFFF',
},
});
```
--------------------------------
### Exporting Utility Functions
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/api-reference/utilities.md
Demonstrates how the utility functions (findKey, findIndex, differenceBy) are exported from the 'src/utils.ts' file. These are internal utilities and not re-exported from the main entry point.
```typescript
export { findKey, findIndex, differenceBy }
```
--------------------------------
### Selective Event Handling: OnDragRelease Only
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/integration-guide.md
A minimal setup where only the final drag release event is handled to update the component's state. This is useful when only the final sorted order is needed.
```typescript
// Only care about final result
}
onDragRelease={(newData) => {
setItems(newData)
}} />
```
--------------------------------
### Responsive Grid Layout Based on Screen Width
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/README.md
Create a responsive grid layout that adjusts the number of columns based on the screen width. This ensures optimal display across different devices and screen sizes.
```typescript
const { width } = useWindowDimensions()
const numColumns = width > 800 ? 4 : width > 600 ? 3 : 2
```
--------------------------------
### Using differenceBy with Different String Property Keys
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/api-reference/utilities.md
Illustrates that the differenceBy function can compare arrays of objects using any string property as the identifying key, not just 'key'. This example uses 'id' to compare user objects.
```typescript
const users1 = [
{ id: 'u1', email: 'alice@example.com' },
{ id: 'u2', email: 'bob@example.com' },
]
const users2 = [
{ id: 'u1', email: 'alice@example.com' },
]
const unmatched = differenceBy(users1, users2, 'id')
// [{ id: 'u2', email: 'bob@example.com' }]
```
--------------------------------
### Tap Gesture Flow
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/api-reference/Block.md
Outlines the sequence of events from a user tap on a block to the execution of the onPress callback.
```text
User taps on block
↓
TouchableWithoutFeedback detects press
↓
onPress callback fires after delay threshold
↓
DraggableGrid.onBlockPress() → props.onItemPress()
```
--------------------------------
### Calculating blockPositions
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/internals.md
Demonstrates how to calculate the cached positions for each grid cell based on its column and row, using the blockWidth and blockHeight.
```typescript
blockPositions[order] = { x: blockWidth * col, y: blockHeight * row }
```
--------------------------------
### IOrderMapItem Interface
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/types.md
An interface used internally to map item keys to their current order or position within the grid.
```typescript
interface IOrderMapItem {
order: number
}
```
--------------------------------
### Manage drag state to prevent item removal during drag
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/troubleshooting.md
Prevent items from getting stuck during drag by managing a drag state. Ensure that items are not removed while a drag operation is in progress. Wait for the onDragRelease event before updating data.
```typescript
const [isDragging, setIsDragging] = useState(false)
setIsDragging(true)}
onDragRelease={(newData) => {
setItems(newData)
setIsDragging(false)
}}
/>
// Don't remove items while isDragging
if (!isDragging) {
removeItemButton()
}
```
--------------------------------
### Optimistic Updates with Rollback
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/README.md
Implement optimistic updates for a smoother user experience. The UI updates immediately, and the data is persisted in the background. Rollback to the old data if the persistence fails.
```typescript
{
setItems(newData) // Update immediately
api.save(newData) // Persist in background
.catch(() => setItems(oldData)) // Rollback on error
}}
/>
```
--------------------------------
### Load items incrementally for large datasets
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/troubleshooting.md
When dealing with a large number of items, paginate or implement virtual scrolling to improve performance. This snippet shows how to load a subset of items initially.
```typescript
// Load items incrementally
const visibleItems = items.slice(0, 50)
```
--------------------------------
### Re-export Pattern Implementation
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/module-exports.md
Illustrates the re-export pattern used by the package. The source file ('draggable-grid.tsx') contains the actual component and types, while the entry point ('index.ts') re-exports them for the public API.
```typescript
// draggable-grid.tsx (source of truth)
export interface IDraggableGridProps { ... }
export const DraggableGrid = function(...) { ... }
// index.ts (public API entry point)
import { IDraggableGridProps, DraggableGrid } from './draggable-grid'
export { DraggableGrid }
export type { IDraggableGridProps }
export default DraggableGrid
```
--------------------------------
### Block Component Structure
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/api-reference/Block.md
Illustrates the nested structure of the Block component, showing how Animated.View and TouchableWithoutFeedback are used.
```typescript
{children}
```
--------------------------------
### Importing Utility Functions Explicitly
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/api-reference/utilities.md
Shows the explicit import statement required to use the utility functions (findKey, findIndex, differenceBy) if they are needed directly from their source file.
```typescript
import { findKey, findIndex, differenceBy } from 'react-native-draggable-grid/src/utils'
```
--------------------------------
### DraggableGrid Event Lifecycle
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/README.md
Illustrates the sequence of events triggered during user interaction with the DraggableGrid component, from initial tap to item release.
```text
1. Tap (without drag)
└─ onItemPress()
2. Long-press (300ms default)
└─ onDragItemActive()
3. Drag starts
└─ onDragStart()
4. Dragging (continuous)
└─ onDragging()
5. Item swaps
└─ onResetSort()
6. Release
└─ onDragRelease()
```
--------------------------------
### Optimize images before rendering
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/troubleshooting.md
Ensure images are optimized for size and performance before rendering them within the grid. Use appropriate styling and resize modes.
```typescript
// ✅ Optimize images before rendering
```
--------------------------------
### Build Command
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/module-exports.md
Command to compile TypeScript code to JavaScript using npm or yarn. The compilation process outputs the JavaScript files into the 'built/' directory.
```bash
npm run built # or yarn built
```
--------------------------------
### Implementing Touch Feedback in DraggableGrid
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/integration-guide.md
Provide haptic feedback on item activation using React Native's Vibration API. This enhances user experience by confirming interaction.
```typescript
export function GridWithFeedback() {
const handleDragItemActive = (item: Item) => {
// Haptic feedback (React Native)
import { Vibration } from 'react-native'
Vibration.vibrate(50)
}
return (
}
onDragItemActive={handleDragItemActive}
onDragRelease={(newData) => setItems(newData)}
/>
)
}
```
--------------------------------
### Generic Type Usage for findKey
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/api-reference/utilities.md
Illustrates the use of generic types with the findKey utility function, specifying the type of the value being searched for.
```typescript
// findKey is generic over the value type
const value = findKey(orderMap, item => item.order === 1)
```
--------------------------------
### Initialize Block Positions from Grid Order
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/internals.md
Populates the blockPositions array by iterating through all items and calculating their respective positions using getBlockPositionByOrder. This operation is linear with respect to the number of items.
```typescript
function initBlockPositions() {
items.forEach((_, index) => {
blockPositions[index] = getBlockPositionByOrder(index)
})
}
```
--------------------------------
### Sizing Item Components Correctly
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/troubleshooting.md
Ensure that the components returned by `renderItem` have intrinsic size or are styled with flex properties to occupy space within the grid.
```typescript
// ❌ Wrong - item has no intrinsic size
renderItem={(item) => {item.name}}
// ✅ Correct - explicit sizing or flex
renderItem={(item) => (
{item.name}
)}
```
--------------------------------
### Memoizing Render Items for Performance
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/integration-guide.md
Optimize grid performance by memoizing the `renderItem` function using `useMemo`. This prevents unnecessary re-renders of list items when the component re-renders.
```typescript
import { useMemo } from 'react'
export function OptimizedGrid() {
const [items, setItems] = useState(initialItems)
const renderItem = useMemo(
() => (item: Item) => ,
[]
)
return (
setItems(newData)}
/>
)
}
```
--------------------------------
### Drag Movement Flow
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/api-reference/Block.md
Illustrates the sequence of events during a drag movement, from PanResponder activation to Block position updates and swap detection.
```plaintext
PanResponder.onPanResponderMove fires continuously
↓
panHandlers attached to outer Animated.View
↓
DraggableGrid.onHandMove() updates currentPosition
↓
Block position changes via Animated value
↓
Swap detection + props.onDragging callback
```
--------------------------------
### TypeScript Implementation: findKey
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/api-reference/utilities.md
Provides the implementation for the findKey utility function. It iterates through object keys and returns the first key that satisfies the predicate function.
```typescript
function findKey(map: { [key: string]: T }, fn: (item: T) => boolean) {
const keys = Object.keys(map)
for (let i = 0; i < keys.length; i++) {
if (fn(map[keys[i]])) {
return keys[i]
}
}
}
```
--------------------------------
### Native Alternative: Array.prototype.findIndex
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/api-reference/utilities.md
Shows the native JavaScript equivalent of the findIndex utility function for modern environments.
```javascript
// Using native findIndex (available in modern environments)
const idx = items.findIndex(item => item.key === 'b') // 1
// Manual implementation in utils.ts is for compatibility
```
--------------------------------
### Debugging Drag Release with Console Logs
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/troubleshooting.md
This diagnostic script uses `useState` and `console.log` to track the state of items and verify that `onDragRelease` and `onResetSort` callbacks are functioning correctly.
```typescript
function testDragRelease() {
const [items, setItems] = useState([
{ key: '1', name: 'A' },
{ key: '2', name: 'B' },
])
console.log('Current items:', items.map(i => i.key))
return (
{item.name}}
onDragRelease={(newData) => {
console.log('onDragRelease called with:', newData.map(i => i.key))
setItems(newData)
}}
onResetSort={(newData) => {
console.log('onResetSort called with:', newData.map(i => i.key))
}}
/>
)
}
```
--------------------------------
### Optimistic State Updates on Drag Release
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/troubleshooting.md
For a smoother user experience, implement optimistic updates by setting the new state immediately upon `onDragRelease`, then persisting the changes in the background.
```typescript
// ❌ Wrong - update happens after render
onDragRelease={(newData) => {
// network call
api.save(newData).then(() => setItems(newData))
}}
// ✅ Correct - optimistic update
onDragRelease={(newData) => {
setItems(newData) // Update immediately
api.save(newData) // Persist in background
}}
```
--------------------------------
### Selective Event Handling: OnDragging and OnDragRelease
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/integration-guide.md
This snippet demonstrates handling both the continuous drag progress ('onDragging') for real-time updates (e.g., progress bars) and the final 'onDragRelease' for state updates.
```typescript
// Monitor drag progress without rendering changes
}
onDragging={(gestureState) => {
updateProgressBar(gestureState.moveX)
}}
onDragRelease={(newData) => {
setItems(newData)
}} />
```
--------------------------------
### Reducing Long-Press Delay for Drag
Source: https://github.com/shisme/react-native-draggable-grid/blob/master/_autodocs/troubleshooting.md
This solution demonstrates how to reduce the `delayLongPress` prop to 150ms to improve responsiveness for drag gestures.
```typescript
// Solution 1: Reduce long-press delay
}
/>
```