Choosing a root element in a hierarchy without affecting the chosen style of a child

I am working on a MUI TreeView component that includes Categories as parents and Articles as children. Whenever I select a child item, it gets styled with a "selected" status. However, when I click on a parent item, the previously selected child loses its "selected" styling.

Is there a way to differentiate between a "child selected" state and a "parent clicked (selected)" state? I would like to achieve this using only CSS if possible. The project is built using Next.js.

Here is the CSS for CategoryItem:

const StyledCategoryItemRoot = styled(TreeItem)(({ theme }) => ({
  [`& .${treeItemClasses.content}`]: {
    fontWeight: theme.typography.fontWeightBold,
    marginBottom: 5,
    paddingLeft: 0,
    borderRadius: theme.shape.borderRadius,
    '&.Mui-selected.Mui-focused, &:hover, &.Mui-selected:hover': {
      backgroundColor:
        theme.palette.mode === 'light'
          ? alpha('#ff9aff', 0.16)
          : alpha('#2f506f', 0.24),
    },
    '&.Mui-selected, &.Mui-focused': {
      backgroundColor: 'transparent',
    },
  },
}));

And here is the CSS for ArticleItem:

const StyledArticleItemRoot = styled(TreeItem)(({ theme, router, post }) => ({
  color:
    theme.palette.mode === 'light'
      ? theme.palette.grey[900]
      : theme.palette.grey[500],
  [`& .${treeItemClasses.content}`]: {
    fontWeight: theme.typography.fontWeightBold,
    paddingLeft: 0,
    borderRadius: theme.shape.borderRadius,
    transition: '.2s',
    '&.Mui-selected:hover, &.Mui-selected.Mui-focused:hover, &:hover': {
      color: theme.palette.mode === 'light' ? theme.palette.grey[800] : 'white',
    },
    '&.Mui-focused, &.Mui-selected, &.Mui-selected.Mui-focused': {
      backgroundColor:
        theme.palette.mode === 'light'
          ? alpha('#ff9aff', 0.16)
          : alpha('#2f506f', 0.16),
      color:
        post.attributes.slug !== router.query.slug
          ? theme.palette.grey[500]
          : theme.palette.mode === 'light'
          ? theme.palette.primary.main
          : theme.palette.secondary.main,
    },
  },
}));

Answer №1

When using the MUI tree view component with multiselect turned off (multiSelect={false}), only one node (parent or child) can be selected at a time. It is not possible to select both parent and child nodes simultaneously.

If a child node is selected first and then the parent node is selected, the child will lose its selected style as it is no longer considered selected.

Regarding the question in the comments:

The desire is to click on the Categories dropdown without losing the "selected" styling on Article.

This can be achieved by manually handling the selection of nodes:

<TreeView
   aria-label="file system navigator"
   key="treeView"
   defaultCollapseIcon={<ExpandMoreIcon />}
   defaultExpandIcon={<ChevronRightIcon />}
   multiSelect={false}
   selected={selectedNodes}
   onNodeSelect={(e, node_ids) => {
     handleClick(e, node_ids);
   }}> //add tree nodes here 
</TreeView>

In the handleClick function, set the selected nodes:

setSelectedNodes(nodes_ids);

To ensure that only the node label is selected (and not the dropdown or collapsible icon), update the handleClick function as follows:

function handleClick(e, nodes_ids) {
  if (e.target.className == "MuiTreeItem-label") 
   setSelectedNodes(nodes_ids);
}

Note: Remember to add selectedNodes to your state:

[selectedNodes, setSelectedNodes]=useState([]);

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

Troubleshooting problems with mapping over data in NextJS using react-query

I recently transitioned to using NextJS (version 13.4.12) and decided to give react-query a try for data fetching. Before adopting react-query, I had been using a custom useFetch hook that was functioning properly. To implement react-query as per recommen ...

The issue encountered with NextJS Link and next/script is that the Script fails to load upon navigation, yet it functions properly when using the <a> tag

I am currently developing an application that requires loading the "https://accounts.google.com/gsi/client" API. I utilized the Script component of NextJS, but when attempting to navigate using the Link from NextJS, the script fails to load again. However, ...

Passing input parameters from a jQuery dialogue box to a handler file (.ashx) in ASP.NET: A step-by-step guide

Hey everyone! I've set up a jQuery dialog box with two input fields as shown below: <div id="dialog" title="Login"> <form action="" method="POST" id="loginForm"> Username: <input type="text" name="username" /><b ...

The compilation of the module has encountered an error with the PostCSS loader. There is a SyntaxError at line 2, character 14 indicating an unknown

I am developing an Angular 8 application. Currently, I am incorporating AlertifyJs into my project. In the styles.css file of Angular, I have imported these libraries: @import '../node_modules/alertifyjs/build/alertify.min.js'; @import '. ...

How disabling SSR is causing my styles to break in Nextjs

My Nextjs app is causing some issues with styling when I disable SSR to connect to Metamask using the window object. Specifically, the Navbar title style changes when SSR is disabled and the dev server is restarted: With SSR enabled: https://i.sstatic.net ...

Error in Mathquill: Unable to access the 'prototype' property because it is undefined

I'm currently in the process of integrating MathQuill into a project I'm developing. After installing the package through NPM (npm install mathquill), I included the following <script> tags in the <head>: <script src="../node_ ...

Can material-ui codemod v5 be implemented in a project that utilizes flow types?

I am looking to transition from material-ui v4 to v5. When I try to use the codemode with: npx @mui/codemod v5.0.0/preset-safe . it is not working for me, especially in files where flowjs types are declared like this: (which applies to all my files) type ...

Tips for finding information within a table using HTML

My task involves creating a table with the option for users to search data within it. However, I have encountered an issue where I am only able to search for data in the first row of the table. <table style="width:100%" id="table"> <tr> ...

What are the steps to determine if a radio has been examined through programming?

In my form page, users can input an ID to fetch profile data from a MySQL database using AJAX. The retrieved data is then displayed in the form for editing. One part of the form consists of radio buttons to select a year level (e.g., "1", "2", "3", etc). ...

Placeholder for empty values in Angular UI mask

Currently, I have implemented the angular ui mask directive for a date field. However, it is inserting underscores as a placeholder. Is there a way to display nothing in the placeholder instead? ...

Reveal hidden elements once the form has been submitted

At this moment, the info, stat and foo elements are hidden. Strangely, when I submit the form, they don't become visible. However, if I incorporate the unhide() function within the <button onclick="unhide()"></button>, it works p ...

What methods are commonly used to calculate the bitsPerSecond rate for media recording?

Is there a specific formula that combines frames per second and resolution to determine the bits per second for video encoding? I'm struggling to figure out the appropriate values to use for specifying the bits per second for 720p, 1080p, and 4k video ...

The NestJs project fails to display the updates when using the "tsc" command before running either "npm run start" or "npm run start:dev"

As a beginner in nestjs, I decided to start a tutorial to learn more about it. However, whenever I make updates or changes to my code, I don't see any changes reflected in the results. Can someone please assist me with this issue? Below are my tsconfi ...

Upon script load, a random item from an array will be displayed and recorded in a separate array

I'm working on a fun code project where I aim to display random animal names in different colors that change when a specific keyboard key is pressed. The challenge I'm facing is that the first random animal name in a random color only appears aft ...

Unique Input Values in Forms

I'm encountering an issue with a basic HTML form connected to a PHP script for processing values. Despite thorough testing, the form is not functioning correctly. Upon inspecting the form markup, I discovered: <form id="delete_item_3_form" action ...

Display the table once the radio button has been selected

Before we proceed, please take a look at the following two images: image 1 image 2 I have over 20 fields similar to 'Image 1'. If "Yes" is selected, then a table like in 'Image 2' should be displayed. This means I have 20 Yes/No fields ...

Apply a specific class using JavaScript/jQuery when a user selects a specific timezone from the user interface

Currently, I am coding in HTML with the code below extracted from this website link. The listings under timezone ET are all correct as they align with the accurate dates; however, for other timezones (PT, MT, CT, AT, NT) some shows seem to be on incorrect ...

What is the best way to ensure that Link and IconButton stay aligned on the same line?

I need to have a hyperlink with a long description and a "copy" symbol following it. The challenge is ensuring that the symbol always appears next to the text and not on a separate line. For example, these links are acceptable: https://i.stack.imgur.com/ ...

Issue with Javascript variables

In Javascript, I have an array of strings that I need to use for loading images on my page through AJAX. After each image is loaded, there are additional tasks to be performed which include sending a HTTP request to delete the image. Below is the code I c ...

I found myself pondering the method to achieve the slightly blue tinted box that sits behind the image

Can you assist me in achieving this specific look? I have my MUI app bar and home page set up, but I'm unsure how to create the blue-ish box behind the image. Should I place the container within my app bar or integrate it into my homepage file? Additi ...