Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Controlled Environment - Expand/Collapse All, Drag and Drop #254

Unanswered
natetewelde asked this question in Q&A
Discussion options

I was previously using an uncontrolled environment to accomplish about 90% of what I needed until I ran across loading data from a DB. I then decided to make the switch over to a controlled environment and found that the data updated the tree correctly with the fetched items. Now I'm struggling to find any documentation surrounding how to utilize drag and drop as well as DOM manipulation with a controlled environment. Everything I've seen so far has just been around uncontrolled environments.

You must be logged in to vote

Replies: 1 comment

Comment options

here's a simple implementation that mimics the UncontrolledTreeEnvironment:

const onDrop = (items: TreeItem<TreeItemData>[], target: DraggingPosition) => {
 if (target.targetType === "between-items") {
 setData((prevData) => {
 if (!prevData) return prevData;
 const parentNode = prevData[target.parentItem];
 const insertIndex = target.childIndex;
 const itemIds = items.map((item) => item.index);
 // Remove the items from their previous parent
 Object.values(prevData).forEach((item) => {
 if (item.children) {
 item.children = item.children.filter((child) => !itemIds.includes(child));
 }
 });
 // Add the items to the new parent at the new position
 const newData = {
 ...prevData,
 [parentNode.index]: {
 ...parentNode,
 children: [
 ...(parentNode.children ?? []).slice(0, insertIndex),
 ...itemIds,
 ...(parentNode.children ?? []).slice(insertIndex),
 ],
 },
 };
 return newData;
 });
 }
 if (target.targetType === "item") {
 setData((prevData) => {
 if (!prevData) return prevData;
 const parentNode = prevData[target.targetItem];
 const itemIds = items.map((item) => item.index);
 // Remove the items from their previous parent
 Object.values(prevData).forEach((item) => {
 if (item.children) {
 item.children = item.children.filter((child) => !itemIds.includes(child));
 }
 });
 // Add the items to the new parent
 const newData = {
 ...prevData,
 [parentNode.index]: {
 ...parentNode,
 children: [...(parentNode.children ?? []), ...itemIds],
 },
 };
 return newData;
 });
 }
 };
You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants

AltStyle によって変換されたページ (->オリジナル) /