Uncovering the unique properties of custom Items in MUI v5 - RichTreeView: A Step-by-Step Guide

Can custom item properties received asynchronously with MUI - RichTreeView be exposed inside a custom treeItem?

For instance, how can the customProperty1 and customProperty2 be accessed within the CustomTreeItem? The console.log to props only shows default properties like id, label, etc.

I opted for RichTreeView because my dataset is going to be extensive.

const ITEMS = [
      {
         id: '1',
         label: 'label1',
         customProperty1: false,
         customProperty2: 'ADD',
      },
   
   const CustomTreeItem = forwardRef((props, ref) => {
      
      const { id, itemId, label, disabled, children, ...other } = props;

      const { getRootProps, getContentProps, getIconContainerProps, getLabelProps, getGroupTransitionProps, status } = useTreeItem2({
         id,
         itemId,
         children,
         label,
         disabled,
         rootRef: ref,
      });

      console.log('props', props);

      return (
         <TreeItem2Provider itemId={itemId}>
            <TreeItem2Root {...getRootProps(other)}>
               <CustomTreeItemContent {...getContentProps()}>
                  <Box sx={{ flexGrow: 1 }}>
                     <Stack direction="row" alignItems="center">
                        <TreeItem2IconContainer {...getIconContainerProps()}>
                           <TreeItem2Icon status={status} />
                        </TreeItem2IconContainer>

                        <TreeItem2Label {...getLabelProps()} />
                     </Stack>
                     {!children && (
                        <Stack direction="row" justifyContent="flex-start" sx={{ pl: 2, ml: 2, mt: 1, backgroundColor: '#2F3B5F', borderRadius: 10, px: 2, my: 1 }}>
                           All spare parts (xxxxx)
                           <Stack sx={{ ml: 'auto' }}>(folder icon here)</Stack>
                        </Stack>
                     )}
                  </Box>
               </CustomTreeItemContent>
               {children && <TreeItem2GroupTransition {...getGroupTransitionProps()} />}
            </TreeItem2Root>
         </TreeItem2Provider>
      );
   });


    <RichTreeView
       aria-label="icon expansion"
       sx={{ position: 'relative' }}
       items={ITEMS}
       slots={{ item: CustomTreeItem }}
   />
   

Edit: A possible solution could be adding this code inside the CustomTreeItem, but there are concerns about potential slowdowns in rendering with huge datasets.

console.log('customProperty1', ITEMS.find((item) => item.id === itemId)?.customProperty1);
   

Answer №1

One method to solve the issue is by utilizing the publicAPI object that is provided after calling the useTreeItem2 function which contains a getItem method.

For instance:

const CustomTreeItem = forwardRef((props, ref) => {
   const { id, itemId, label, disabled, children, ...other } = props;

   const { getRootProps, getContentProps, getIconContainerProps, getLabelProps, getGroupTransitionProps, publicAPI, status } = useTreeItem2({
      id,
      itemId,
      children,
      label,
      disabled,
      rootRef: ref,
   });

   
   console.log('items=>', publicAPI.getItem(itemId));
   

   return (
      <TreeItem2Provider itemId={itemId}>
         <TreeItem2Root {...getRootProps(other)}>
            <CustomTreeItemContent {...getContentProps()}>
               <Box sx={{ flexGrow: 1 }}>
                  <Stack direction="row" alignItems="center">
                     <TreeItem2IconContainer {...getIconContainerProps()}>
                        <TreeItem2Icon status={status} />
                     </TreeItem2IconContainer>

                     <TreeItem2Label {...getLabelProps()} />
                  </Stack>
                  {!children && (
                     <Stack direction="row" justifyContent="flex-start" sx={{ pl: 2, ml: 2, mt: 1, backgroundColor: '#2F3B5F', borderRadius: 10, px: 2, my: 1 }}>
                        All spare parts (xxxxx)
                        <Stack sx={{ ml: 'auto' }}>(folder icon here)</Stack>
                     </Stack>
                  )}
               </Box>
            </CustomTreeItemContent>
            {children && <TreeItem2GroupTransition {...getGroupTransitionProps()} />}
         </TreeItem2Root>
      </TreeItem2Provider>
   );
});

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 point of utilizing angular.extend in this situation?

After inheriting a codebase, I stumbled upon the following code snippet (with some parameters simplified and anonymized): /** * @param {float} num1 * @param {string} str1 * @param {string} str2 * @param {boolean} flag & @return (object) */ sr ...

modifying the click state using a variable in jquery

Something feels off about my approach to this task. I currently have a series of hyperlinks, and when they are clicked, they go through a short sequence before changing states. When clicked again, they revert to their original state. var favourites = fun ...

Encountered a 404 error (not found) while making a GET request with axios

I encountered an issue with my pizza shop application built with Next.js. Whenever I run the app on my computer, I come across this error: https://i.sstatic.net/tsQzZ.png The error disappears after refreshing the page. Here is my index.js file: import ax ...

Using javascript to eliminate a block of HTML code

In my AngularJS project, I am using owl-carousel and attempting to reinitialize the carousel after a change in data by using $(element).data('owlCarousel').destroy(); while also removing this block: <div class="owl-wrapper"> <div class= ...

Unusual display of feedback text in Bootstrap 4

When I directly copied this code snippet from Bootstrap 4: <div class="form-group has-danger"> <label class="form-control-label" for="inputDanger1">Input with danger</label> <input type="text" class="form-control form-contro ...

What are the steps to integrating an HTML source with jQuery Autocomplete?

Struggling with a challenging ajax call to an HTML source that is essential. The goal is to convert the html response into a format suitable for displaying in the jQuery autocomplete list. Working with Autocomplete and Ajax $("#From, #To, #FromVacation ...

Performing AJAX in Rails4 to update boolean values remotely

Suppose I have a model named Post which includes a boolean attribute called active. How can I efficiently modify this attribute to either true or false directly from the list of posts in index.html.erb using link_to or button_to helper along with remote: ...

Ways to confirm the validation of radio buttons in a form and implement CSS

I am having trouble adding validation to a form with radio buttons displayed as labels. I want to show a red border around the radios/labels or outer div when a radio button hasn't been checked before the user submits the form. I have attempted this ...

Clicking on an icon to initiate rotation (Material UI)

Is there a way to toggle the rotation of an icon (IconButton) based on the visibility of a Collapse component? I want it to point down when the Collapse is hidden and up when it's shown. const [expanded, setExpanded] = useState<boolean>(false); ...

What is the reason why the show() function in JQuery only applies to one specific element, rather than all elements selected with the same selector?

JSFiddle. This example code features a nested <table> within another <table>. The main issue concerns the click listener for the #add button. Specifically, the final if/else statement in the function. When you execute this code and click the ...

Unable to use console log in shorthand arrow function while working with Typescript

When debugging an arrow function in JavaScript, you can write it like this: const sum = (a, b) => console.log(a, b) || a + b; This code will first log a and b to the console and then return the actual result of the function. However, when using TypeSc ...

The getBBox() method of SVG:g is returning an incorrect width value

Hey there, I've been attempting to determine the width of a <g> element and it consistently returns 509.5 pixels regardless of what I do. Initially, I assumed this was the actual size and not scaled. However, upon opening the SVG in Illustrato ...

Is your Ajax jQuery live search not functioning properly with JSON data?

My programming code is not functioning properly. Here is the file I am working on. When it does work, it does not display the list and gives an error in the Json file. I am unsure of the reason behind this issue. You will be able to view the error in the C ...

How can we automate the process of assigning the hash(#) in Angular?

Is it possible to automatically assign a unique hash(#) to elements inside an ngFor loop? <div *ngFor="let item of itemsArray; index as i"> <h3 #[item][i]> {{ item }} </h3> </div> I would like the outp ...

What is the best way to retrieve the value of an input field in React when incorporating Material UI components?

I am working with a few radio input components that have been imported from material Ui react. Each radio input is wrapped in a FormControlLabel component. <FormControlLabel onClick={checkAnswerHandler} value={answer} control={<Radio color=&quo ...

Creating a decorative ribbon in three.js for your gift presentation

How can I create a ribbon for a gift box using three.js, similar to the example shown here: Is it possible to create the ribbon with just one piece or do I need multiple pieces to achieve the desired look? Thank you :) ...

(Javascript - Arrays) Find the leftmost and rightmost connected characters

Looking for the leftmost and topmost connected '1' character in a 2D matrix? Find the most left & top connected '1' character Find the most right & bottom connected '1' character EDIT 2.0: To start, provide the coordina ...

Utilizing React Router Dom to Showcase Home Route from a Sub-Route

www.mywebsite.com www.mywebsite.com/ www.mywebsite.com/1 I need my website to show the same content for each of the links above. Currently, it is not displaying anything for www.mywebsite.com and www.mywebsite.com/ function App() { return ( <Rout ...

Issue with Express - Session not persisting across consecutive SSE requests

Currently, I am delving into Server-sent Events using Node.js and Express. I have successfully set up request handling and stream writing, but I am facing challenges with session management. The session does not persist between subsequent calls. Snippet o ...

What could be causing my node.js to fail in producing a true result within the return statement?

I've encountered an issue with VS code where the return true command is not displaying anything in my terminal, while console.log(map[arr2[j]]) successfully returns true. I'm unsure if this problem lies with node or my terminal. How can I ensure ...