Adding borders to the TreeView component in Material-UI: A step-by-step guide

I have some React code here and I'm trying to display dashed lines on the left of a tree. How can I achieve this effect?

I am looking for something similar to this:

https://i.sstatic.net/w64VL.png

Additionally, I want to combine the style of TreeView with the following code snippet:

const StyledTreeItem = withStyles((theme) => ({
        iconContainer: {
            '& .close': {
                opacity: 0.3,
            },
        },
        group: {
            marginLeft: 2,
            paddingLeft: 3,
            borderLeft: `1px dashed ${fade(theme.palette.text.primary, 0.4)}`,
        },
    }))((props) => <TreeItem {...props} />);

https://codesandbox.io/s/green-surf-dcoqr?fontsize=14&hidenavigation=1&theme=dark&file=/src/tree.js:0-2494

"organizationalUnitsList": [
    {
      "organizationalUnitId": "",
      "organizationalUnitName": "A",
      "organizationalUnitsList": [
        {
          "organizationalUnitId": "",
          "organizationalUnitName": "b",
        }
      ]
    },
    {
      "organizationalUnitId": "",
      "organizationalUnitName": "C",
      "organizationalUnitsList": [
        {
          "organizationalUnitId": "",
          "organizationalUnitName": "D",
          "organizationalUnitsList": [
            {
               "organizationalUnitId": "",
               "organizationalUnitName": "e",
            }
         ]
        }
      ]
    },
    {
      "organizationalUnitId": "",
      "organizationalUnitName": "f"
    }

]

Currently, I don't want TreeView to display a borderBottom at OrganizationalUnitName like 'A', 'C', and 'D' as they will be considered parents of their child. I only want the child elements to show a borderBottom.

There are multiple organizationalUnitId values present, but whenever an array of objects is displayed, I want them to appear as children rather than parents. How can I accomplish this?

Answer №1

Learn how to enhance the appearance of your tree structure by adding vertical borders to each TreeItem. For horizontal borders, simply create a pseudo element for every TreeItem and utilize absolute positioning for accurate placement. Here's an example implementation:

import TreeItem, { treeItemClasses } from "@mui/lab/TreeItem";

type StyledTreeItemProps = {
  rootNode?: boolean;
};

const StyledTreeItem = styled(TreeItem)<StyledTreeItemProps>(({ rootNode }) => {
  const borderColor = "gray";

  return {
    position: "relative",
    "&:before": {
      pointerEvents: "none",
      content: '""',
      position: "absolute",
      width: 32,
      left: -16,
      top: 12,
      borderBottom:
        // only display if the TreeItem is not root node
        !rootNode ? `1px dashed ${borderColor}` : "none"
    },

    [`& .${treeItemClasses.group}`]: {
      marginLeft: 16,
      paddingLeft: 18,
      borderLeft: `1px dashed ${borderColor}`
    }
  };
});

Implementation

<TreeView>
  <StyledTreeItem rootNode nodeId="1" label="Applications">
    <StyledTreeItem nodeId="2" label="Calendar" />
    <StyledTreeItem nodeId="3" label="Drive" />
  </StyledTreeItem>
  <StyledTreeItem rootNode nodeId="8" label="Documents">
    <StyledTreeItem nodeId="9" label="OSS" />
    <StyledTreeItem nodeId="10" label="MUI">
      <StyledTreeItem nodeId="11" label="index.js" />
    </StyledTreeItem>
  </StyledTreeItem>
</TreeView>

Check it out live!

Version 5

https://codesandbox.io/s/69596143-how-to-style-react-material-ui-treeitems-label-forked-3j852?file=/demo.tsx

Version 4

https://codesandbox.io/s/66946584how-to-customize-the-treeview-in-react-with-material-ui-8ym32?file=/src/tree.js

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 are some ways to adjust the size of the option field in a select menu?

In my ionic popup, I have a HTML property called select with nested options. Below is the code snippet along with the applied CSS. My query is how can I set the white space to occupy the entire area of the select? https://i.stack.imgur.com/iPqAa.png http ...

What impact does the CSS float property have on line height and element positioning?

I'm facing an issue where I have a table cell with a button inside it. When I try to float this button, it not only moves horizontally but also changes its vertical position, shifting to the top of the line. For example: <table style="width: 100% ...

How can I extract a list of errors from this JSON object in a React.js application?

Is there a way to extract the list of errors from the following JSON object using React js? data = { "container_1587015390439_0001_01_000004": { "ERROR":["20/04/16 05:43:51 ERROR CoarseGrainedExecutorBackend: RECEIVED SIGNAL TERM"] , ...

Utilizing factory service within a decorator in AngularJS

Utilizing the TextAngular plugin and attempting to customize a toolbar, I am striving to inject my own service (LinkService) into the module but encountering an [$injector:unpr] Unknown provider issue. module.config(function($provide, LinkService){ $p ...

Is it possible to incorporate a React app as a component within a static HTML page?

Looking to integrate the react-csv-viewer component into a static HTML page without deploying it on a local server. I've tried following the instructions from the React tutorial, but am struggling with the build process. My goal is simple - to use th ...

Retrieve properties of the chosen MenuItem from a Select component in Material UI

My custom component const myUniqueComponent = ({ title, data, errors, onSubmit, groups }) => { const [state, setState] = useState( Object.assign( { username: "", password: "", group: "", isAdmin: false, ...

Is it justifiable to stop providing support for javascript-disabled or non-ajax browsers in secure applications?

I'm intrigued by the current trend in ajax applications. Is it acceptable to focus on building the best ajax application possible and disregard browsers that don't support ajax (especially if it's a secured part of the site and not public)? ...

Following the update of the password, the user encounters issues logging in

I'm encountering a major issue when trying to update user information using the fetch PUT method. Everything seems to be working correctly as I receive an encrypted password, but when I attempt to log in with the updated data, it shows as incorrect. F ...

Saving a value in a service using AngularJS

I am facing an issue with passing a variable into a service that needs to be accessed from multiple states within my application. I have created a service and attempted to pass a variable from a controller into the service in order to access it from anothe ...

Why does Cloudinary fail to delete the tmp folder it creates after finishing the upload process?

Recently, I've been working on implementing an upload Post feature for my app. The process involves submitting a file from the frontend, sending it to the backend, and then uploading it to Cloudinary's cloud servers. However, before the upload to ...

What is the process for constructing an object to resemble another object?

After collecting input data, I have created an object based on those values. Here is an example of the generated object: var generate_fields = { name: "Mike", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b4d9dddf ...

What is the best way to smoothly transition from one video to another with a simple click?

I am looking to enhance my website by implementing a feature where a video will play when a button is clicked, and then another video will smoothly fade in while fading out the current video upon clicking a different button. This transition should dynamica ...

Increasing box width in Django

I'm currently working on a website using Django all-auth for authentication. Everything is functioning perfectly, but I'm wondering if there's a way to increase the size of the username and password input boxes using HTML. Below is the code ...

Encountering an issue while defining a parameter in an Angular component: expecting either a property

Encountering an issue when attempting to set a parameter involving numbers first, as required by openweathermap's API. Specifically, the data retrieval for rain is labeled as '3h', thus requiring me to input 'data.rain.3h'. However ...

When a single column is achieved, aligning with justify-content space-between

I'm working on styling a div that has two children using flexbox and flex-wrap. I want the layout to adjust without needing media queries - so that when it reaches a certain width, the children are spaced evenly (justify-content: space-between), but w ...

What is the best way to combine a string on the controller side in order to automatically populate a form

I am working on a Bootstrap form where users enter their email address. If the user doesn't include '@scoops.com' in their email, I need to automatically concatenate it either on the front end or backend using the controller. In the control ...

What is the best way to avoid duplicating this JQM function multiple times and instead reuse it efficiently?

After coming across this interactive demo, I successfully implemented it on my website using JQM. However, in order to activate the panel swipe feature, I had to include the following function: $( document ).on( "pagecreate", "#demo-page", function() { ...

When running on Docker and accessed via an IP, the UI is unable to connect to the Node server

Currently, I am faced with a dilemma involving Docker Containers. 1. node/Play/any Backend Server 2. React 3. Other services I have successfully launched them through docker-compose and everything is running smoothly. However, an issue has arisen: When I ...

Combine year and month in 2 separate divs using the fullcalendar format: <div>Year</div> <div>Month</div>

Can someone help me with a coding issue I'm facing? I am trying to split the title of a calendar into two separate divs - one for the year at the top of the page and one for the month at the top of the calendar. I have tried using angular.element but ...

Are the links drifting to the left?

Some of the links on my website seem to be misbehaving and not following the CSS rules, floating to the left unexpectedly. Strangely, it's only the links that are affected; the rest of the text appears fine. For example, you can observe this issue at ...