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

Modify the input field in the datepicker to resemble a button

How can I transform an input field into a button that looks like this rather than this ? The simple switch of tag names doesn't seem to work. Any suggestions on how to achieve this? class MyComponent extends React.Component { componentDidMount() ...

What is the best way to create non-standard text wrapping in HTML and CSS that is both semantic and sleek, avoiding square or circular shapes?

Is there a way to achieve text wrapping like this using semantic and clean HTML and CSS that is compatible with all browsers? The only solution I can think of is adding different classes to the <p> element. However, the drawback of this approach is ...

The Reason Behind Component Non-ReRendering in Redux

I am currently facing an issue with my component and reducer. The `componentDidMount()` method in my component is calling a server to get some data, but the component doesn't re-render after the action is performed. I have checked my code multiple tim ...

Error: inability to execute performanceMeasurement.startMeasurement due to its absence in the function definition

An error occurred when attempting to login using @azure/msal-react in Next 13. Upon checking the error log, it was found that the error originated from the core library @azure/msal-react. Even after trying with a login popup, the error persisted. In my co ...

When the browser is refreshed, jQuery will automatically scroll the window down

I created a div that matches the height and width of the window to simulate a "home screen." When scrolling down to view the content, everything works fine. However, after refreshing the browser, it automatically scrolls back to where you were before. I wa ...

React struggling to retrieve the initial value from localStorage

Hello everyone! I am currently working on a MERN app and have been exploring how to implement JWT token authentication. Everything seems to be working fine, but I encountered a small issue on the frontend. After a user logs in, the token is successfully se ...

Frontend React app encountering communication issue with backend API via proxy connection

Error: Request to /api/v1/products from localhost:3000 could not be proxied to . Refer to https://nodejs.org/api/errors.html#errors_common_system_errors for details (ETIMEDOUT). This issue persists. Frontend -> React Backend -> Express, Node.js ...

Showing the writer on an individual blog post layout

I have successfully generated multiple author pages programmatically by extracting data from the yaml file provided below: data/author.yaml - id: jane_doe name: Jane Doe twitter: jane_doe bio: Chillwave lumbersexual chicharrones tote bag. Brunch ...

Is there a way to determine if jQuery lightslider has been initialized, and if so, how can I effectively remove the instance?

Currently, I have integrated the JQuery lightSlider into my project. Despite some code adjustments, it is functioning well. My goal is to dynamically replace the lightSlider content with data returned via AJAX, which I have successfully achieved. After r ...

Placing a background image behind the text of an <a> tag

I am wondering if it is possible to change the position of a background-image without affecting the text in a link. <a href="#" style="background-image: url('bg.png')">text</a> Can the background-image be moved independently of ...

Determine the source of the user's arrival on a specific URL

Currently, I have an onboarding page similar to this www.abc.com/ that welcomes users. Returning users are directed to /set-profile image page. This page contains a Submit button. My objective is for users who click the Submit button to be redirected to ...

Guide for implementing smooth fade in and out effect for toggling text with button click

I have this code snippet that toggles text on button click: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> function toggleText(){ ...

Is it possible to use both material-ui@next and the previous version concurrently?

I need some advice on a project I am working on that utilizes material-ui@next (v1). While I appreciate the new features in the latest autocomplete, I find it too complex for my needs. Instead, I would like to revert back to the older version of the autoco ...

Converting Epoch time to date in NextJS

In my NextJS app, I have a date displayed in a div. <div>{post.createdat}</div> The date is shown in epoch time (1609553315666), indicating the number of seconds that have elapsed since 1970. I'm wondering if there's a way to conver ...

Nginx try_files not functioning properly for serving css and images

I am attempting to route any requests that come from https://example.com/user/whatever to my "Get Our App" page located at https://example.com/get_app.html Within my nginx.conf file, I have configured the following block: #Redirecting all requests under ...

Unexpected resizing of DIV element in Chrome

Working on my new PHP website, I encountered a strange issue recently. I have a file for the top navbar that is included on every page and it was functioning perfectly fine. However, while creating a register form, I noticed something odd happening. When r ...

Looking for assistance with Redux and React Hooks - anyone?

I have created an interactive image gallery where users can click between page one and page two. When a user clicks on an image, a modal will appear displaying the selected image along with its title and description. There is also a Submit Button that allo ...

Discover the best practices for implementing the metadata API within Next.js 13 while effectively utilizing context

Having trouble displaying layout.tsx with the default theme because it requires a theme provider and involves useContext. This causes Next.js to raise server-side rendering errors. To work around this, I added the 'use client' field to the docume ...

Tips for personalizing the ToolbarComponent for the Material-UI KeyboardDatePicker component in React.js

Hello, I am currently using React along with Material-UI and KeyboardDatePicker. If you want to check out the code, you can find it here: https://codesandbox.io/s/material-demo-forked-rt1f1?file=/index.js import "date-fns"; import React from &quo ...

Developing an interactive web interface with HTML

I've been attempting to design a flexible HTML page that replicates the layout of a Java applet clock, but I'm unsure if my current approach is correct. Below is an example of the three-clock image set that I am currently working on. My method i ...