Exploring the ins and outs of utilizing pseudo selectors with material-ui

I've been attempting to accomplish a simple task. I wanted to toggle the visibility of my <TreeMenu/> component in material UI v1 using pseudo selectors, but for some reason it's not working. Here is the code: CSS:

      root: {
        backgroundColor: 'white',
        '&:hover': {
          backgroundColor: '#99f',
        },
      },

  hoverEle: {
    visibility: 'hidden',
    '&:hover': {
      visibility: 'inherit',
    },
  },
      rootListItem: {
        backgroundColor: 'white',
        display: 'none',
        '&:hover': {
          display: 'block',
          backgroundColor: '#99f',
        },
      },
      '@global': {
        'li > div.nth-of-type(1)': {
          display: 'block !important',
          backgroundColor: "'yellow',",
        },
      },

The root css class works fine on the list, but rootListItem and even the @global li selector do not work. I'm unsure of what I'm doing wrong with these selectors. I've read the material-ui docs which state that V1 supports pseudo selectors.

JSX:

<div>
      {props.treeNode.map(node => (
        <ListItem
          key={`${node.Type}|${node.NodeID}`}
		  id={`${node.Type}|${node.NodeID}`}
          className={(classes.nested, classes.root)}
          button
          divider
          disableGutters={false}
          dense
          onClick={() => props.onNodeClick(node.Type, node.NodeID, node.NodeName)}
          title={props.adminUser ? node.NodeID : ''}
          onMouseOver={() => props.onMouseOver(node.Type, node.NodeID)}
        >
          <ListItemIcon>{props.listIcon}</ListItemIcon>
          <ListItemText primary={node.NodeName} />
          <ListItemSecondaryAction classes={{ root: classes.rootListItem }}>
            <TreeMenu />
          </ListItemSecondaryAction>
          <div className={classes.hoverEle}>
            <TreeMenu />
          </div>
        </ListItem>
      ))}
    </div>

Please pay attention to the <TreeMenu > component. I've tried 3 different methods: 1) Using hoverEle class with '&:hover' selector. 2) Attempting to override the default root class of <ListItemSecondaryAction> with my class rootListItem. 3) Utilizing other pseudo selectors on li. See 'li > div.nth-of-type(1)':

Answer №1

It took some time to troubleshoot your code and identify the issue.

Although the selector for rootListItem is functioning properly, the problem lies in using the :hover pseudo-selector on an element with display: none. To work around this, consider using opacity: 0 and opacity: 1 instead. This will hide ListItemSecondaryAction while allowing for hover effects. Elements with display: none cannot be hovered over as they technically do not display.

In regards to the global pseudo-selector, there was a mistake in its implementation. You should use a dot instead of a colon after div and change backgroundColor to 'yellow' without the extra quotes.

'li > div:nth-of-type(1)': {
        display: 'block !important',
        backgroundColor: 'yellow',
    },

I wasn't sure about the structure of your TreeMenu component, so I simulated it with a list containing ul / li / div nodes.

const styles = {
root: {
    backgroundColor: 'white',
    '&:hover': {
        backgroundColor: '#99f',
    },
},
hoverEle: {
    visibility: 'hidden',
    '&:hover': {
        visibility: 'inherit',
    },
},
rootListItem: {
    backgroundColor: 'white',
    opacity: 0,
    '&:hover': {
        opacity: 1,
        backgroundColor: '#99f',
    },
},
'@global': {
    'li > div:nth-of-type(1)': {
        display: 'block !important',
        backgroundColor: "yellow",
    },
},
};

And:

<div>
    {treeNode.map(node => (
        <ListItem
            key={`${node.Type}|${node.NodeID}`}
            id={`${node.Type}|${node.NodeID}`}
            className={classes.root}
            button
            divider
            disableGutters={false}
            dense
            onClick={() => {}}
            title={''}
            onMouseOver={() => {}}
        >
            <ListItemText primary={node.NodeName} />
            <ListItemSecondaryAction classes={{ root: classes.rootListItem }}>
                <ul><li><div>Elem 1</div></li><li><div>Elem 2</div></li></ul>
            </ListItemSecondaryAction>
            <div className={classes.hoverEle}>
                <ul><li><div>Elem 1</div></li><li><div>Elem 2</div></li></ul>
            </div>
        </ListItem>
    ))}
</div>

*I am utilizing treeNode as an array and have excluded additional functions and TreeMenu related details.

Answer №2

While collaborating with Jorge Santos Neil, it is important to note that props are not always required. Here is an example that has been tested for a different scenario. It should be noted that this code snippet must be included in the "makeStyles" function and then used as a className. Simply placing it inside "styles={{}}" will not yield the desired result.

For instance:

const useStyles = makeStyles((theme) => ({
  paragraphWithWarningDiv: {
    margin: "32px 0px 24px",
    "& :nth-child(1)": {
      marginBottom: "100px"
    }
  }
}));

Answer №3

The method that proved effective for me is as follows

export const applyStyles = makeStyles(theme=>({
        header:{
            position: "relative!important",
            background: "linear-gradient(150deg,#7795f8 15%,#6772e5 70%,#555abf 94%)",
            margin: -50,
            padding: -50,
            height: 500,
        },

        span: props => ({
            padding:50,
            background: "rgba(255, 255, 255, .1)",
            borderRadius: "50%",
            position: "absolute",
            "&:nth-child(1)": {
                left: "-4%",
                bottom: "auto",
                background: "rgba(255, 255, 255, .1)"
            },
            "&:nth-child(2)":{
                right: "4%",
                top: "10%",
                background: "rgba(255, 255, 255, .1)"
            },
            "&:nth-child(3)":{
                top: 280,
                right: "5.66666%",
                background: "rgba(255, 255, 255, .3)"
            },
            "&:nth-child(4)":{
                top: 320,
                right: "7%",
                background: "rgba(255, 255, 255, .15)"
            },
            "&:nth-child(5)":{
                top: "38%",
                left: "1%",
                right: "auto",
                background: "rgba(255, 255, 255, .05)"
            },
            "&:nth-child(6)": {
                width: 200,
                height: 200,
                top: "44%",
                left: "10%",
                right: "auto",
                background: "rgba(255, 255, 255, .15)"
            },
            "&:nth-child(7)": {
                bottom: "50%",
                right: "36%",
                background: "rgba(255, 255, 255, .04)"
            },
            "&:nth-child(8)": {
                bottom: 70,
                right: "2%",
                background: "rgba(255, 255, 255, .2)"
            },
            "&:nth-child(9)": {
                bottom: "1%",
                right: "2%",
                background: "rgba(255, 255, 255, .1)"
            },
            "&:nth-child(10)": {
                bottom: "1%",
                left: "1%",
                right: "auto",
                background: "rgba(255, 255, 255, .05)"
            }

        }),

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

Organizing playing cards in a React JS application

As a beginner just starting out with React JS, I'm working on arranging cards in a medium size for my application. I came across a card design that I like and I'm seeking help to achieve something similar. Any assistance would be greatly apprecia ...

Lean/Tilt just the lower portion of the division

I have been experimenting with adding a unique slant to the bottom of a div. Progress has been made, as shown in the example below where I successfully applied the slant to some elements on the page. Currently, the slant is visible on both the top and bot ...

Prevent event propagation when clicking on an Autocomplete material UI component within an accordion section

I am facing an issue with adding an Autocomplete component inside an AccordionSummary. Whenever I click on it, the accordion expands and enters a focus state. I have tried to stop the propagation of events, but unfortunately, it has not been successful. ...

Avoiding HTML (JSX) tag duplication in React Component

Having the same code in my React component multiple times is becoming repetitive and inefficient. Is there a way to follow the DRY principle and avoid repeating this code? While creating a landing page with Sass styling, I noticed that I am duplicating t ...

What is the best way to create a dropdown menu that smoothly slides in from the bottom of the screen?

Is it possible to create dropdown menus in the navigation bar that slide in from the bottom with a smooth transition effect, similar to this example: Although I am working on building my own template, so my code may differ from the original theme. Here is ...

The parsing of the React module in webpack failed due to an error with ReactDOM

Recently, I've been diving into the insights offered by the surviveJS ebook as I attempt to configure webpack for my ReactJS projects. However, when attempting to run my start script, a perplexing error arises: An error in ./app/index.js Module pa ...

"Trouble arises when dealing with nested object arrays in Formik and handling changes in a child

I am struggling with passing a value to handleChange in formik validation. To address this issue, I created a component whose quantity is dynamically added based on the number of numChild. My goal is to allow users to click an icon and add any number of sk ...

Having trouble with uploading images on Amazon S3 and sharing them on Facebook? Learn how to set the correct meta tag "og:image" in Next

As I work on coding to enable sharing my website page on Facebook, I have utilized meta tags for open graphs. Previously, the images were stored on the server and linked in the meta tag like this: <meta key="og:image" property="og:image" content ...

JavaScript CompleteLink message

Hey there, I've come across a JavaScript code for a countdown timer but need some assistance with it. The issue I'm facing is that within the code, there's a line that displays a message to the user when the timer reaches zero. I want to kn ...

Issue with Bootstrap 4 navbar dropdown on mobile: unable to click on menu item

My website is currently in development with Bootstrap 4. I'm facing an issue where, on mobile devices, when the menu items collapse into the three bars, they are not clickable. Despite following the recommendations in the Bootstrap documentation, the ...

Having trouble getting Tailwind custom colors to work in my Next.js project

When I try to assign the custom colors configured in tailwind.config.js to a variable and use it, it doesn't work as expected. For example: If we have button.colour = "custom-blue" (color data fetched from the cms and set in the cms) <button class ...

Trigger a function when clicking outside the element, similar to how a Bootstrap modal is closed

I have successfully created a popup box using angular in my project. It appears when I click on an icon and disappears when I click on the close button. However, I would like it to also close if someone clicks outside of the popup. Can anyone help me with ...

What is the best method to encourage users to download the app instead of the mobile web by displaying a banner?

I have built my website using React. I am looking to display a banner when users access the site on an iPhone or Android phone, encouraging them to download and use the dedicated iOS or Android app instead of browsing on their mobile browser. How can I ach ...

The text stubbornly refusing to conform to a single line

I am currently experiencing an issue where the text inside the anchor tag is not adjusting to a single line. Below is my HTML code: <html> <head> <link rel="stylesheet" href="style5.css" type="text/css"> </head> ...

The surprising margins that Bootstrap sneaks into columns

It seems like bootstrap is mysteriously including an unseen margin in my column classes. Even after inspecting an element labeled as 'col-lg-3,' there is no visible margin CSS, and attempting to manually add margin:0 still results in a margin bei ...

What is the best way to change my state with a function triggered by a click event?

I am currently developing a simple rock paper scissors app that utilizes an array containing 'rock', 'paper', and 'scissors'. My goal is to map through this array and update the state through the handle click function when the ...

Sliding Navigation Panel

Currently, I am attempting to implement a sidebar push navigation that mimics the one showcased here. My HTML structure includes content within a center element div. The code snippet is as follows: <div id="mySidenav" class="sidenav"> <a href="j ...

A guide on defining the width of an element within a flex container when it overflows

Here is the code snippet I have: .divA { background: red; width: 500px; display: flex; flex-direction: row; overflow-y: scroll; } .epi { width: 50%; background: blue; } <div class="divA"> <div class="epi"> <h1>dsds ...

Activate event using jQuery in webpack and manage it on the page

I'm currently in the process of revamping a large application using React. One challenge I've encountered is refreshing a datatable on the page after a successful form submission, as the datatable isn't controlled by React or webpack. I trie ...

Arranging HTML elements with jQuery - the existing script flips back and forth

I have created a code snippet on CodePen that showcases a feature of the website I am currently developing: http://codepen.io/barrychapman/pen/BzJGbg?editors=1010 Upon loading the page, you will notice 6 boxes. The first box is active, while the remaining ...