### Minimal Treeview Setup
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/QUICK-REFERENCE.md
A basic setup for the Tree component within a DndProvider. This example shows how to provide the tree data, root ID, and a render function for nodes.
```typescript
(
{node.text}
)}
onDrop={(newTree) => setState(newTree)}
/>
```
--------------------------------
### Install react-dnd-treeview
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/QUICK-REFERENCE.md
Install the library using npm. Ensure react-dnd is also installed.
```bash
npm install react-dnd @minoru/react-dnd-treeview
```
--------------------------------
### Minimal Tree Component Setup
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/README.md
Basic setup for the Tree component, requiring an array of nodes, a root ID, and a render function. Optional props can be added for further customization.
```typescript
import { Tree } from '@minoru/react-dnd-treeview';
ReactElement}
onDrop={(tree, options) => void}
// ... optional props
/>
```
--------------------------------
### Configure MultiBackend
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/configuration.md
Utilize the MultiBackend for a recommended setup that supports both HTML5 and Touch interactions. It requires importing `MultiBackend` and `getBackendOptions`.
```typescript
import { DndProvider } from 'react-dnd';
import { MultiBackend, getBackendOptions } from '@minoru/react-dnd-treeview';
```
--------------------------------
### Install react-dnd-treeview
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/README.md
Install the necessary packages for react-dnd-treeview using npm.
```shell
npm i react-dnd @minoru/react-dnd-treeview
```
--------------------------------
### Configuring Backends with Options
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/README.md
Provides an example of how to pass specific options to HTML5Backend, TouchBackend, or MultiBackend. Ensure options are correctly typed and passed to the DndProvider.
```jsx
import { DndProvider } from "react-dnd";
import { HTML5Backend, HTML5BackendOptions } from "react-dnd-html5-backend";
import {TouchBackend, TouchBackendOptions} from "react-dnd-touch-backend"
import {Tree, MultiBackend, getBackendOptions} from "@minoru/react-dnd-treeview"
const touchOptions: Partial = {
// some options
};
const html5Options: Partial = {
rootElement: document.body,
// some options
};
const multiOptions = {
touch: touchOptions,
html5: html5Options,
}
function App() {
return (
/>
);
}
```
--------------------------------
### Basic Tree Setup
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/usage-examples.md
The minimal configuration to display a draggable tree. Requires importing Tree, getBackendOptions, MultiBackend from '@minoru/react-dnd-treeview' and DndProvider from 'react-dnd'.
```typescript
import { useState } from 'react';
import { Tree, getBackendOptions, MultiBackend } from '@minoru/react-dnd-treeview';
import { DndProvider } from 'react-dnd';
function App() {
const [treeData, setTreeData] = useState([
{ id: 1, parent: 0, text: 'Folder 1', droppable: true },
{ id: 2, parent: 1, text: 'File 1.1' },
{ id: 3, parent: 1, text: 'File 1.2' },
{ id: 4, parent: 0, text: 'Folder 2', droppable: true },
{ id: 5, parent: 4, text: 'File 2.1' },
]);
const handleDrop = (newTree) => {
setTreeData(newTree);
};
return (
(
{hasChild && (
)}
{node.text}
)}
onDrop={handleDrop}
/>
);
}
export default App;
```
--------------------------------
### AnimateHeight Example Usage
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/components.md
Demonstrates how to use the AnimateHeight component with custom easing, duration, and variants to animate content visibility.
```jsx
{children}
```
--------------------------------
### Basic TreeView Usage
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/README.md
Demonstrates the basic setup for the Tree component, including state management for tree data and a custom render function for nodes. Requires initial data and a DndProvider.
```jsx
import { useState } from "react";
import {
Tree,
getBackendOptions,
MultiBackend,
} from "@minoru/react-dnd-treeview";
import { DndProvider } from "react-dnd";
import initialData from "./sample-default.json";
function App() {
const [treeData, setTreeData] = useState(initialData);
const handleDrop = (newTreeData) => setTreeData(newTreeData);
return (
(
)}
/>
);
}
```
--------------------------------
### ItemTypes Usage Example
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/components.md
Illustrates how to import and potentially use the ItemTypes constant, although its primary use is internal for drag type identification.
```javascript
import { ItemTypes } from '@minoru/react-dnd-treeview';
// Used internally for drag type identification
const { ItemTypes } = monitor.getItemType();
```
--------------------------------
### File Organization Structure
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/README.md
Illustrates the directory structure of the react-dnd-treeview project, showing the location of README, quick reference, types, configuration, usage examples, and API reference files.
```tree
output/
├── README.md (this file)
├── QUICK-REFERENCE.md (fast lookup)
├── types.md (type definitions)
├── configuration.md (configuration guide)
├── usage-examples.md (code examples)
└── api-reference/
├── tree-component.md (Tree component API)
├── utility-functions.md (utility functions)
├── hooks.md (custom hooks)
├── providers.md (context providers)
└── components.md (internal components)
```
--------------------------------
### Implement Multi-Tree Dragging
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/usage-examples.md
This example shows how to enable dragging and dropping items between two separate tree components. Both trees are configured to accept items from each other, allowing for cross-tree manipulation.
```typescript
function MultiTree() {
const [tree1, setTree1] = useState([...]);
const [tree2, setTree2] = useState([...]);
// Both trees accept items from each other
const handleDropTree1 = (newTree) => setTree1(newTree);
const handleDropTree2 = (newTree) => setTree2(newTree);
return (
Tree 1
(
{hasChild && }
{node.text}
)}
onDrop={handleDropTree1}
/>
Tree 2
(
{hasChild && }
{node.text}
)}
onDrop={handleDropTree2}
/>
);
}
```
--------------------------------
### Importing DndProvider and Tree component (v2.x)
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/MIGRATION.md
From v2.x onwards, react-dnd is no longer included. Users must install react-dnd separately and import DndProvider.
```jsx
import { DndProvider } from "react-dnd";
import {
Tree,
MultiBackend,
getBackendOptions,
} from "@minoru/react-dnd-treeview";
function App() {
return (
);
}
```
--------------------------------
### Example of Treeview Data with Custom Properties
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/README.md
This JSON structure demonstrates how to add custom 'data' objects to nodes, including file type and size, which can be utilized in custom rendering logic.
```json
[
{
"id": 1,
"parent": 0,
"droppable": true,
"text": "Folder 1"
},
{
"id": 2,
"parent": 1,
"text": "File 1-1",
"data": {
"fileType": "csv",
"fileSize": "0.5MB"
}
},
{
"id": 3,
"parent": 1,
"text": "File 1-2",
"data": {
"fileType": "pdf",
"fileSize": "4.8MB"
}
},
{
"id": 4,
"parent": 0,
"droppable": true,
"text": "Folder 2"
},
{
"id": 5,
"parent": 4,
"droppable": true,
"text": "Folder 2-1"
},
{
"id": 6,
"parent": 5,
"text": "File 2-1-1",
"data": {
"fileType": "image",
"fileSize": "2.1MB"
}
}
]
```
--------------------------------
### Track Tree Expansion State Changes
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/usage-examples.md
Listen to expansion state changes by providing a callback function to the `onChangeOpen` prop. This example logs the IDs of currently open folders to the console.
```typescript
function TreeWithEvents() {
const [tree, setTree] = useState([...]);
const [openFolders, setOpenFolders] = useState([]);
const handleChangeOpen = (newOpenIds) => {
console.log('Folders now open:', newOpenIds);
setOpenFolders(newOpenIds);
};
return (
Currently expanded: {openFolders.join(', ')}
(
{hasChild && }
{node.text}
)}
onDrop={(newTree) => setTree(newTree)}
/>
);
}
```
--------------------------------
### Styled Tree with Icons
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/usage-examples.md
Add styling and material icons to the tree component. This example uses CSS modules for styling and imports FolderIcon and FileIcon from '@mui/icons-material'.
```typescript
import { useState } from 'react';
import { Tree, getBackendOptions, MultiBackend } from '@minoru/react-dnd-treeview';
import { DndProvider } from 'react-dnd';
import FolderIcon from '@mui/icons-material/Folder';
import FileIcon from '@mui/icons-material/InsertDriveFile';
import styles from './Tree.module.css';
function StyledTree() {
const [tree, setTree] = useState([...]);
return (
(
)}
onDrop={(newTree) => setTree(newTree)}
/>
);
}
```
--------------------------------
### Basic Classes Configuration
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/configuration.md
Define CSS class names for styling various elements of the Tree component. This example shows the structure for applying classes to the root, container, list items, drop targets, dragging source, and placeholder.
```typescript
const classes = {
root: "tree-root",
container: "tree-container",
listItem: "tree-item",
dropTarget: "tree-drop-target",
draggingSource: "tree-dragging",
placeholder: "tree-placeholder",
};
```
--------------------------------
### Create a Custom Tree Provider Wrapper
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/providers.md
Wrap the Tree component with additional providers to inject custom context. The Tree component handles its own provider setup internally.
```typescript
import { Tree } from '@minoru/react-dnd-treeview';
function CustomTreeWrapper(props) {
const [customState, setCustomState] = useState(null);
return (
);
}
```
--------------------------------
### Creating a Custom Component Using Tree Context
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/hooks.md
Provides an example of how to create a custom component that utilizes the useTreeContext hook to access tree state, including the tree data, open node IDs, and root ID. This allows for displaying statistics or performing other operations based on the tree's current state.
```typescript
import { useTreeContext } from '@minoru/react-dnd-treeview';
function TreeStats() {
const { tree, openIds, rootId } = useTreeContext();
const parentCount = tree.filter(n => n.droppable).length;
const childCount = tree.filter(n => !n.droppable).length;
return (
Total nodes: {tree.length}
Folders: {parentCount}
Files: {childCount}
Open nodes: {openIds.length}
);
}
// Inside a Tree component:
{/* Works because it's inside Tree */}
```
--------------------------------
### Accessing Tree Methods with useRef
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/tree-component.md
Demonstrates how to use the useRef hook to get a reference to the TreeMethods, allowing programmatic control over the tree component.
```typescript
const treeRef = useRef(null);
```
--------------------------------
### Custom Tree Node Rendering
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/README.md
Use the render prop to customize how each tree node is displayed. This example shows how to indent nodes based on their depth and add toggle buttons for droppable nodes.
```jsx
(
)}
/>
```
--------------------------------
### Implement Undo/Redo Support for Tree
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/usage-examples.md
This example demonstrates how to add undo and redo functionality to a tree component by tracking its state history. It manages a history array and an index to navigate through previous and future states.
```typescript
function TreeWithHistory() {
const [tree, setTree] = useState([...]);
const [history, setHistory] = useState([[...]]);
const [historyIndex, setHistoryIndex] = useState(0);
const handleDrop = (newTree) => {
const newHistory = history.slice(0, historyIndex + 1);
newHistory.push(newTree);
setTree(newTree);
setHistory(newHistory);
setHistoryIndex(newHistory.length - 1);
};
const handleUndo = () => {
if (historyIndex > 0) {
const newIndex = historyIndex - 1;
setTree(history[newIndex]);
setHistoryIndex(newIndex);
}
};
const handleRedo = () => {
if (historyIndex < history.length - 1) {
const newIndex = historyIndex + 1;
setTree(history[newIndex]);
setHistoryIndex(newIndex);
}
};
return (
(
{hasChild && }
{node.text}
)}
onDrop={handleDrop}
/>
);
}
```
--------------------------------
### Implement Custom Drop Rules
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/usage-examples.md
Enforce custom validation logic to determine where nodes can be dropped. This example prevents dropping into 'locked' folders and prevents dropping onto self or same parent.
```typescript
function RestrictedTree() {
const [tree, setTree] = useState([
{ id: 1, parent: 0, text: 'Protected Folder', droppable: true, data: { locked: true } },
{ id: 2, parent: 0, text: 'Normal Folder', droppable: true },
{ id: 3, parent: 2, text: 'File' },
]);
const canDrop = (treeData, { dragSourceId, dropTargetId, dragSource, dropTarget }) => {
// Cannot drop into locked folders
if (dropTarget?.data?.locked) {
return false;
}
// Cannot drop on self or same parent
if (dragSourceId === dropTargetId || dragSource?.parent === dropTargetId) {
return false;
}
return true;
};
return (
(
)}
onDrop={(newTree) => setTree(newTree)}
/>
);
}
```
--------------------------------
### getParents()
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/utility-functions.md
Get all ancestor nodes up to the root. This function is helpful for determining the path or hierarchy of a specific node.
```APIDOC
## getParents()
### Description
Get all ancestor nodes up to the root.
### Method
```typescript
function getParents(
treeData: NodeModel[],
id: NodeModel["id"]
): NodeModel[]
```
### Parameters
#### Tree Traversal
- **treeData** (NodeModel[]) - Required - Complete tree array
- **id** (string | number) - Required - Node ID to get parents for
### Returns
`NodeModel[]` - Array of parent nodes from immediate parent up to root (excludes the node itself)
### Example
```typescript
import { getParents } from '@minoru/react-dnd-treeview';
const parents = getParents(treeData, 7);
console.log('Breadcrumb:', parents.map(p => p.text).reverse());
// Breadcrumb: ['Root', 'Folder 1', 'Subfolder 2', 'Current Folder']
```
```
--------------------------------
### Provider Hierarchy
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/providers.md
Illustrates the nesting order of providers within the react-dnd-treeview component, starting from DndProvider down to the Node components.
```plaintext
DndProvider (from react-dnd)
└─ Tree component
└─ Providers wrapper
└─ TreeProvider
└─ DragControlProvider
└─ PlaceholderProvider
├─ DragLayer (if dragPreviewRender)
└─ Container
└─ Node (recursive)
```
--------------------------------
### Link Local Package to Project
Source: https://github.com/minop1205/react-dnd-treeview/wiki/How-to-check-package-operation-locally
Navigate to the package directory, link it globally, then link it to the target project's node_modules. Ensure you are in the correct directories for each command.
```bash
cd react-dnd-treeview
npm link && npm link --legacy-peer-deps ../myapp/node_modules/react
cd ../myapp
npm link @minoru/react-dnd-treeview
```
--------------------------------
### Get Destination Index
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/utility-functions.md
Calculates the absolute array index of a drop destination. Used to determine the final position of a node when dropped.
```typescript
function getDestIndex(
tree: NodeModel[],
dropTargetId: NodeModel["id"],
index: number
): number
```
```typescript
import { getDestIndex } from '@minoru/react-dnd-treeview';
const absoluteIndex = getDestIndex(tree, parentId, 2);
// Returns the absolute index of the 3rd child of parentId
```
--------------------------------
### getBackendOptions()
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/utility-functions.md
Configure backend options for MultiBackend drag and drop with both pointer and touch support. This function helps in setting up the DndProvider with appropriate backend configurations for seamless drag and drop interactions.
```APIDOC
## getBackendOptions()
### Description
Configure backend options for MultiBackend drag and drop with both pointer and touch support.
### Method
```typescript
function getBackendOptions(options?: {
html5?: Partial;
touch?: Partial;
}): MultiBackendOptions
```
### Parameters
#### Options Object
- **options** (object) - Optional - Configuration object
- **options.html5** (Partial) - Optional - HTML5 backend options (only rootElement supported)
- **options.touch** (Partial) - Optional - Touch backend options; enableMouseEvents allows touch backend to handle mouse events (Default: `{ enableMouseEvents: true }`)
### Returns
`MultiBackendOptions` - Configuration object compatible with `DndProvider backend prop`
### Example
```typescript
import { DndProvider } from 'react-dnd';
import { MultiBackend, getBackendOptions } from '@minoru/react-dnd-treeview';
function App() {
return (
{/* Tree component */}
);
}
```
```
--------------------------------
### Configure HTML5 Backend
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/configuration.md
Set up the drag and drop provider to use the HTML5 backend for drag and drop functionality.
```typescript
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
```
--------------------------------
### Get Tree Item by ID
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/utility-functions.md
Retrieves a specific node from the tree array using its unique ID. Returns undefined if the node is not found.
```typescript
function getTreeItem(
tree: NodeModel[],
id: NodeModel["id"]
): NodeModel | undefined
```
```typescript
import { getTreeItem } from '@minoru/react-dnd-treeview';
const node = getTreeItem(tree, 5);
if (node) {
console.log(`Found: ${node.text}`);
} else {
console.log('Node not found');
}
```
--------------------------------
### Importing All Hooks
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/hooks.md
Demonstrates how to import all available hooks from the '@minoru/react-dnd-treeview' package in a single statement.
```typescript
import {
useContainerClassName,
useDragControl,
useDragHandle,
useDragNode,
useDragOver,
useDropNode,
useDropRoot,
useOpenIdsHelper,
useTreeContext,
useTreeDragLayer,
} from '@minoru/react-dnd-treeview';
```
--------------------------------
### Configure Touch Backend
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/configuration.md
Configure the drag and drop provider to use the Touch backend, suitable for touch-enabled devices.
```typescript
import { DndProvider } from 'react-dnd';
import { TouchBackend } from 'react-dnd-touch-backend';
```
--------------------------------
### Optional dragSourceId and dragSource in onDrop callback (v2.x)
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/MIGRATION.md
In v2.x, dragSourceId and dragSource were always present in the onDrop options. This example shows the older usage.
```jsx
{
console.log(options.dragSource.id);
}}
/>
```
--------------------------------
### Custom Tree Wrapper with Drag Preview
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/components.md
Demonstrates creating a custom tree component that wraps the main Tree component to add features like a custom drag preview and header elements. Requires importing DndProvider and HTML5Backend for drag-and-drop functionality.
```typescript
import {
Tree,
Container,
DragLayer,
ItemTypes,
} from '@minoru/react-dnd-treeview';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
function CustomTree(props) {
return (
File Explorer
(
📄 {item.text}
)}
/>
);
}
```
--------------------------------
### Implement Custom Sort Order
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/usage-examples.md
Define a custom sorting function to control the order of child nodes. This example sorts by a 'priority' field first, then alphabetically.
```typescript
function SortedTree() {
const [tree, setTree] = useState([
{ id: 1, parent: 0, text: 'Folder', droppable: true, data: { priority: 1 } },
{ id: 2, parent: 0, text: 'Document', data: { priority: 2 } },
{ id: 3, parent: 0, text: 'Archive', data: { priority: 0 } },
]);
const customSort = (a, b) => {
// Sort by priority first, then alphabetically
const priorityDiff = (a.data?.priority ?? 999) - (b.data?.priority ?? 999);
if (priorityDiff !== 0) return priorityDiff;
return a.text.localeCompare(b.text);
};
return (
(
{hasChild && }
{node.text}
)}
onDrop={(newTree) => setTree(newTree)}
/>
);
}
```
--------------------------------
### Complete Treeview Configuration
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/configuration.md
This snippet demonstrates a full configuration of the Tree component, including core props, styling, drag and drop behavior, expansion options, and custom drag previews. It's useful for setting up a feature-rich, interactive tree view.
```typescript
import { useState, useRef } from 'react';
import { Tree, getBackendOptions, MultiBackend } from '@minoru/react-dnd-treeview';
import { DndProvider } from 'react-dnd';
function TreeApp() {
const treeRef = useRef(null);
const [tree, setTree] = useState([...]);
return (
(
)}
/>
);
}
```
--------------------------------
### Configure MultiBackend Options
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/utility-functions.md
Use getBackendOptions to configure MultiBackend drag and drop with both pointer and touch support. It accepts optional HTML5 and touch backend configurations.
```typescript
function getBackendOptions(options?: {
html5?: Partial;
touch?: Partial;
}): MultiBackendOptions
```
```typescript
import { DndProvider } from 'react-dnd';
import { MultiBackend, getBackendOptions } from '@minoru/react-dnd-treeview';
function App() {
return (
{/* Tree component */}
);
}
```
--------------------------------
### Get Modified Index
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/utility-functions.md
Calculates source and destination indices for array move operations. Automatically adjusts the destination index to account for source removal. Used internally by mutateTreeWithIndex.
```typescript
function getModifiedIndex(
tree: NodeModel[],
dragSourceId: NodeModel["id"],
dropTargetId: NodeModel["id"],
index: number
): [number, number]
```
```typescript
import { getModifiedIndex } from '@minoru/react-dnd-treeview';
const [srcIdx, destIdx] = getModifiedIndex(tree, 5, 3, 1);
```
--------------------------------
### TreeMethods.openAll()
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/tree-component.md
Opens all parent nodes that have children, effectively expanding the entire tree.
```APIDOC
## openAll()
### Description
Opens all parent nodes that have children.
### Signature
```typescript
openAll(): void
```
### Example
```typescript
treeRef.current.openAll();
```
```
--------------------------------
### Custom Drag Validation
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/QUICK-REFERENCE.md
Defines custom rules for which nodes can be dragged using the 'canDrag' prop. This example prevents dragging of nodes that have a 'locked' property set to true in their data.
```typescript
{
return node?.data?.locked !== true;
}}
/>
```
--------------------------------
### Configure MultiBackend with Custom Options
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/configuration.md
Customize the behavior of the HTML5 and Touch backends when using MultiBackend by providing specific options. This allows fine-tuning interactions like root element selection or enabling mouse events for touch.
```typescript
import { getBackendOptions } from '@minoru/react-dnd-treeview';
const options = getBackendOptions({
html5: {
rootElement: document.body,
},
touch: {
enableMouseEvents: true,
}
});
```
--------------------------------
### Get Drop Target
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/utility-functions.md
Determines the drop target node and index based on the current mouse position during drag. Used internally during drag hover to respect dropTargetOffset for zone detection.
```typescript
function getDropTarget(
node: NodeModel | null,
nodeEl: HTMLElement | null,
monitor: DropTargetMonitor,
context: TreeState
): { id: NodeModel["id"]; index: number } | null
```
```typescript
// Typically used internally, but can be used for custom drop logic
const dropTarget = getDropTarget(node, nodeEl, monitor, context);
if (dropTarget) {
console.log(`Dropping on node ${dropTarget.id} at index ${dropTarget.index}`);
}
```
--------------------------------
### Get Ancestor Nodes
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/utility-functions.md
The getParents function retrieves all ancestor nodes up to the root for a given node ID. It returns an array of parent nodes from the immediate parent up to the root, excluding the node itself.
```typescript
function getParents(
treeData: NodeModel[],
id: NodeModel["id"]
): NodeModel[]
```
```typescript
import { getParents } from '@minoru/react-dnd-treeview';
const parents = getParents(treeData, 7);
console.log('Breadcrumb:', parents.map(p => p.text).reverse());
// Breadcrumb: ['Root', 'Folder 1', 'Subfolder 2', 'Current Folder']
```
--------------------------------
### Project File Structure
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/MANIFEST.md
This markdown structure shows the organization of documentation files within the project, indicating the purpose of each file.
```markdown
/workspace/home/output/
├── README.md # Start here
├── QUICK-REFERENCE.md # Fast lookup
├── types.md # Type definitions
├── configuration.md # Configuration guide
├── usage-examples.md # Code examples
├── MANIFEST.md # This file
└── api-reference/
├── tree-component.md # Tree component API
├── utility-functions.md # Utility functions
├── hooks.md # Hooks documentation
├── providers.md # Context providers
└── components.md # Internal components
```
--------------------------------
### Key Utilities
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/README.md
A collection of utility functions for manipulating and querying tree data, including backend configuration, descendant/ancestor retrieval, and drop validation.
```APIDOC
## Key Utilities
### Description
A set of utility functions to assist with tree manipulation, querying, and backend configuration.
### Functions
- **getBackendOptions()**: Configures the MultiBackend for drag and drop.
- **getDescendants(node, tree)**: Retrieves all descendant nodes of a given node.
- **getParents(node, tree)**: Retrieves all ancestor nodes of a given node.
- **hasChildNodes(node, tree)**: Checks if a node has any child nodes.
- **mutateTree(tree, dragOverNode, dropPosition)**: Updates the tree structure, typically for sorting.
- **mutateTreeWithIndex(tree, dragOverNode, dropPosition, index)**: Updates the tree structure with a specific index.
- **isDroppable(node, tree, options)**: Validates whether a node can be dropped at a specific location.
```
--------------------------------
### Using HTML5 Backend for react-dnd
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/README.md
Configure the DndProvider to use the HTML5Backend for drag and drop functionality. This is suitable for web applications.
```jsx
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
function App() {
return (
/>
);
}
```
--------------------------------
### Basic Treeview with Drag and Drop
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/tree-component.md
This snippet shows a functional Tree component with drag-and-drop enabled. It includes state management for tree data and a handler for drop events. Ensure you have react-dnd and its backend installed.
```typescript
import { useState, useRef } from 'react';
import { Tree } from '@minoru/react-dnd-treeview';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
function App() {
const treeRef = useRef(null);
const [treeData, setTreeData] = useState([
{ id: 1, parent: 0, text: 'Folder 1', droppable: true },
{ id: 2, parent: 1, text: 'File 1.1' },
{ id: 3, parent: 1, text: 'File 1.2' },
{ id: 4, parent: 0, text: 'Folder 2', droppable: true },
]);
const handleDrop = (newTree) => {
setTreeData(newTree);
};
return (
(
{node.droppable && (
)}
{node.text}
)}
onDrop={handleDrop}
/>
);
}
```
--------------------------------
### Tree Ref Methods for Node Manipulation
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/QUICK-REFERENCE.md
Demonstrates how to use the ref object to control the open and close states of nodes. This includes methods for individual nodes, multiple nodes, and all nodes.
```typescript
const treeRef = useRef(null);
// Open nodes
treeRef.current.open(id);
treeRef.current.open([id1, id2]);
treeRef.current.openAll();
// Close nodes
treeRef.current.close(id);
treeRef.current.close([id1, id2]);
treeRef.current.closeAll();
```
--------------------------------
### Implement Dynamic Data Loading
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/usage-examples.md
Load children on demand when a folder is expanded. The `handleChangeOpen` function asynchronously fetches child nodes for folders that have `hasChildren` flag set and haven't loaded their children yet.
```typescript
function LazyLoadingTree() {
const [tree, setTree] = useState([
{ id: 1, parent: 0, text: 'Folder 1', droppable: true, data: { hasChildren: true } },
{ id: 2, parent: 0, text: 'Folder 2', droppable: true, data: { hasChildren: true } },
]);
const handleChangeOpen = async (openIds) => {
// For each newly opened folder, load children
for (const nodeId of openIds) {
const node = tree.find(n => n.id === nodeId);
if (node && node.data?.hasChildren) {
// Check if children already loaded
const hasChildren = tree.some(n => n.parent === nodeId);
if (!hasChildren) {
// Simulate loading from API
const children = await simulateLoadChildren(nodeId);
setTree(prev => [...prev, ...children]);
}
}
}
};
return (
(
{hasChild && }
{node.text}
)}
onDrop={(newTree) => setTree(newTree)}
/>
);
}
async function simulateLoadChildren(parentId) {
return new Promise(resolve => {
setTimeout(() => {
resolve([
{ id: Math.random(), parent: parentId, text: `Child 1 of ${parentId}` },
{ id: Math.random(), parent: parentId, text: `Child 2 of ${parentId}` },
]);
}, 500);
});
}
```
--------------------------------
### onDragStart
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/README.md
Event handler fired when a node drag operation begins. Receives the target node and a DragSourceMonitor object.
```APIDOC
## onDragStart
### Description
This event is fired when a node in the tree is started to be dragged. The event handler is passed the target node and a [DragSourceMonitor](https://react-dnd.github.io/react-dnd/docs/api/drag-source-monitor) object.
### Parameters
This prop accepts a function.
### Type
`function`
### Default
`undefined`
```
--------------------------------
### Custom Sort Function
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/configuration.md
Provide a custom comparison function to the 'sort' prop for non-alphabetical ordering of child nodes. This example demonstrates sorting based on a 'priority' property within the node's 'data' object.
```typescript
{
// Sort by custom property in node.data
return a.data?.priority - b.data?.priority;
}}
{...props}
/>
```
--------------------------------
### Opening Multiple Nodes with Callback
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/tree-component.md
Use the `open` method to open multiple nodes by providing an array of IDs. An optional callback function can be provided to execute after the open state changes, receiving the new array of open IDs.
```typescript
treeRef.current.open([1, 2, 3], (newOpenIds) => console.log(newOpenIds));
```
--------------------------------
### Import All Utility Functions
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/utility-functions.md
Imports all utility functions from the react-dnd-treeview library at once. This is a convenient way to access multiple utilities.
```typescript
import {
compareItems,
getBackendOptions,
getDescendants,
getDestIndex,
getDropTarget,
getModifiedIndex,
getParents,
getTreeItem,
hasChildNodes,
isAncestor,
isDroppable,
isNodeModel,
mutateTree,
mutateTreeWithIndex,
} from '@minoru/react-dnd-treeview';
```
--------------------------------
### Opening All Parent Nodes
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/tree-component.md
The `openAll` method expands all parent nodes that contain children, providing a quick way to view the entire tree structure.
```typescript
treeRef.current.openAll();
```
--------------------------------
### TreeProvider
Source: https://github.com/minop1205/react-dnd-treeview/blob/next/_autodocs/api-reference/providers.md
The main context provider that manages the tree's state, configuration, and drag-and-drop logic. It aggregates props, handles open/close states, provides imperative methods, and manages the onDrop callback and drag-and-drop manager access.
```APIDOC
## TreeProvider
### Description
Manages the overall state, configuration, and drag-and-drop logic for the tree.
### Type Signature
```typescript
const TreeProvider: (props: PropsWithChildren & { treeRef: React.ForwardedRef }>) => ReactElement
```
### Provides
`TreeContext>`
### State Structure
```typescript
{
// User-provided props
tree: NodeModel[];
rootId: NodeModel['id'] | undefined;
render: (node: NodeModel) => ReactElement;
classes?: TreeClasses;
// Computed defaults
extraAcceptTypes: NodeModel['type'][];
listComponent: 'ul' | 'ol';
listItemComponent: 'li' | 'div';
placeholderComponent: 'li' | 'div';
sort: boolean;
insertDroppableFirst: boolean;
enableAnimateExpand: boolean;
dropTargetOffset: number;
initialOpen: boolean;
// Computed state
openIds: NodeModel['id'][];
onDrop: (dragSource: NodeModel, dropTargetId: NodeModel['id'], index: number) => void;
onToggle: (nodeId: NodeModel['id']) => void;
// Callbacks
canDrop?: (draggedNode: NodeModel, dropTargetNode: NodeModel) => boolean;
canDrag?: (node: NodeModel) => boolean;
onDragStart?: (node: NodeModel) => void;
onDragEnd?: (node: NodeModel) => void;
}
```
### Access via
```typescript
import { useTreeContext } from '@minoru/react-dnd-treeview';
const treeContext = useTreeContext();
```
### Source
`src/providers/TreeProvider.tsx`
```