React-dnd enhances the functionality of the MUI tree view

I've been using a Material UI v4 Treeview with react-dnd and everything works smoothly. However, when I recently upgraded to MUI v5 Treeview, the drag functionality stopped working - the item is no longer draggable. After comparing the two TreeItem implementations, it seems like there have been significant changes and I'm feeling a bit lost.

If you're interested, here are the links to the respective TreeItem files: v4.x TreeItem and MUI TreeItem.

I would greatly appreciate any insights or suggestions on what might be causing this issue. Thank you in advance for your help :)

//recursive function to generate TreeItem tree with Drag embedded
function Box({ treeItem }) {
  const [{ isDragging }, drag, preview] = useDrag(() => ({
    type: "TREEVIEW",
    item: !treeItem.children.length //if the resource has no child
      ? treeItem.data // we provide only the resource data
      : [
          treeItem.data,
          ...flatten(extractChildren(treeItem), extractChildren).map(
            //other wise we provide resource + child resources
            (x) => delete x.children && x
          ),
        ],
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  }));

  return (
    <>
      <DragPreviewImage connect={preview} src={knightImage} />
      <TreeItem
        nodeId={treeItem.data.TreeID}
        label={treeItem.data.TreeName}
        ref={drag}
        style={{ isDragging }}
      >
        {treeItem.children &&
          treeItem.children.map((treeItem) => <Box treeItem={treeItem} />)}
      </TreeItem>
    </>
  );
}

const renderedListItems = tree.map((treeItem) => (
  <Box treeItem={treeItem} />
));

Answer №1

It is possible that the selection of the tree item occurs when it is clicked on, even though the disableSelection property is true in the TreeView. This results in the clicked child being focused due to the aria-activedescendant property at the root level.

To prevent this focus event, we can include

onFocusCapture={e => e.stopPropagation()}
in the TreeItem component, allowing for smoother dragging and dropping functionality.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for adding an HTML tag that includes an md-checkbox and md-icon?

I am currently utilizing angular material and angular js to dynamically add a new HTML div when a certain function is triggered from the view. Here is my view setup: <div id = "main_row" ng-click="defCtrl.submit()"> </div> This is wh ...

Comparing a series of smaller strings to a larger string for testing purposes

My website has an array filled with bot names. Whenever a user or bot visits the site, I retrieve the user-agent and want to check if any of the values in my array are present in it. var bots = [ "twitterbot", "linkedinbot", "facebookexternalhit", ...

Bootstrap Table encountering issues when displaying JSON data from Ajax response

I am currently struggling with an unusual issue. I have received a successful JSON response from the server, which I need to display in my Bootstrap Table. However, I am facing difficulty in displaying the JSON data in the Bootstrap Table while using AJAX ...

Adjusting image dynamically based on conditions

I need to dynamically display images on my HTML based on specific conditions using TypeScript. In my TypeScript file: styleArray = ["Solitary", "Visual","Auditory","Logical","Physical","Social","Verbal",]; constructor(){ for (var i = 0; this.sty ...

Creating a dynamic list filter using JavaScript and three select boxes

Looking for a way to implement a similar feature to the one on this webpage: I will be showcasing a list of brands on the page, with each brand requiring three pieces of information: Starting letter Store (multiple options) Category (multiple options) ...

Utilizing Custom Validators in Angular to Enhance Accessibility

I'm struggling to access my service to perform validator checks, but all I'm getting is a console filled with errors. I believe it's just a syntax issue that's tripping me up. Validator: import { DataService } from './services/da ...

triggers an unexpected error in console.log

I need help with the following code: function printName(obj) { console.log(obj.name); } printName({ name: "myName" }); (function displayError(errorMsg){ console.log(errorMsg); })("Error"); However, when I try to run this code, I am encountering a T ...

JavaScript Slider for Color Selection

In my slider, I have added a .images class along with buttons for previous and next. To set the colors, I have used JavaScript to define an array like this: let colors = ['red', 'green',]; Currently, clicking the next-button displays ...

When you type a letter in the middle of a string, the cursor is automatically moved back to the end - Material UI

I designed a ChipInput feature that switches to a string when focused and transforms into a Chip component when blurred, with chips separated by commas. Everything seems to be functioning properly except for one issue I am encountering. Whenever I type in ...

Application: The initialization event in the electron app is not being triggered

I am facing an issue while trying to run my electron app with TypeScript and webpack. I have a main.ts file along with the compiled main.js file. To troubleshoot, I made some edits to the main.js file to verify if the "ready" function is being called. ...

How are "new" and "prototype.constructor" related in the realm of Javascript?

Many people have discussed this issue, but unfortunately, I haven't been able to find a solution yet. Here is a snippet of Javascript code regarding inheritance from a book: function Car() { var self = this; self.type = "Car" self.go = funct ...

What might be causing the ng-model in this plunkr to not update as expected?

I recently customized a ui-select plunkr to suit my specific needs. I've noticed that the ng-model is not updating as expected, but interestingly, clicking the button to update the model results in the ui-select getting updated. Any guidance on resol ...

Storing data from a massive JSON array into a separate array using a specific condition in JavaScript

Dealing with a large JSON array can be challenging. In this case, I am looking to extract specific objects from the array based on a condition - each object should have "dbstatus":-3. data = [{"id":"122","dbstatus":-3},{"id":"123","dbstatus":"-6"},{"id" ...

After successfully sending a GET request to the API, the Next.js 13.4.3 website still does not reflect new posts added on the hosting platform

I am currently using Next.js version 13.4.3 in my app directory to create a blog site. However, I am facing an issue. When I run npm run build locally on my computer and then start with npm run start, the new posts are displayed normally after adding them ...

Tips on generating an HTML element using JavaScript and storing it in a MySQL database

I need help with saving a created element to the database so that it remains on the page even after refreshing. Any assistance would be greatly appreciated. Thank you. document.getElementById("insert").onclick = function(){ if(document.getElementById( ...

Processing JSON in PHP after an AJAX POST request

In the scenario where JavaScript is used to make an ajax request: index.js- var dataFeedback = $("#feedback_popup_message_body").val(); var jsonObj = JSON.stringify({dataFeedback: dataFeedback}); $.ajax({ url: "index.php", type: 'POST' ...

What is the reason behind the length property belonging to an array object?

While there are other instances, let's focus on the length property for now. Why does it appear as if we're copying it here: [].hasOwnProperty("length") //==> true It is common knowledge that an array's length property belongs ...

What is the best way to filter an object in AngularJS based on its properties?

I am faced with the issue of filtering two arrays of objects. Below is an example: $scope.countries = [ {'id' : 1, 'country_name':'India'}, {'id' : 10, 'country_name':'Australia'} ...

Exploring how to utilize optional URL parameters within Express.js

When using Express.js version 4.14, I implemented the following route: app.get('/show/:name/:surname?/:address?/:id/:phone?', function(req, res) { res.json({ name: req.params.name, surname: req.params.surname, address ...

Webpack: Live reloading is not functioning properly, however the changes are still successfully compiling

Could someone help me understand why my React application, set up with Webpack hot reload, is not functioning properly? Below is the content of my webpack.config.js: const path = require('path'); module.exports = { mode: 'development&apo ...