Utilizing CSS in JS for nested hover styles with Material UI: a step-by-step guide

I am currently utilizing Material UI and in the process of converting regular CSS classes into a JavaScript file.

.nav {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
}

.navItem {
    float: left;
    flex: 1;
}

.navLink {
    color: white;
    text-decoration: none;
    display: block;
    font-size: '1 rem';
    font-weight: 500;
    line-height: 1.6;
    letter-spacing: '0.0075em';
    opacity: 1;
    text-transform: 'none';
    min-width: 0;
    padding: 10px;
    margin-left: 10px;
    margin-right: 10px;
}

.navLink-static {
    color: white;
    text-decoration: none;
    display: block;
    font-size: '1rem';
    font-weight: 500;
    line-height: 1.6;
    letter-spacing: '0.0075em';
    opacity: 1;
    text-transform: 'none';
    padding: 10px;
    margin-left: 10px;
    margin-right: 10px;
}

.navLink:hover {
    border-bottom: 2px solid mediumvioletred;
    background: #8DB8DD;
    cursor: pointer;
}

 .navLink:hover > div:hover {
      border-bottom: none;
 }

.navLink.active {
    font-weight: 600;
    border-radius: 0;
    border-color: transparent;
    border-bottom: 3px solid orange;
    padding-bottom: 10px;
}
<ul className={classes.nav}>
    <li className={classes.navItem}>
        <NavLink className={classes.navLink} to="/" exact>
            abc
        </NavLink>
    </li>
    <li className={classes.navItem}>
        <NavLink className={classes.navLink} to="/def" exact>
            def
        </NavLink>
    </li>
    <li className={classes.navItem}>
        <NavLink className={classes.navLink} to="/ghi">
            ghi
        </NavLink>
    </li>
</ul>

How do I convert these CSS styles into a material UI pattern? I am struggling with setting an 'active' state and implementing nested hover styles for elements. Additional documentation on advanced scenarios like this would be greatly helpful.

This is my current progress:


const styles = theme => ({
    nav: {
        listStyleType: 'none',
        margin: 0,
        padding: 0,
        overflow: 'hidden'
    },
    navItem: {
        float: 'left',
        flex: 1
    },
    navLink: {
        color: 'white',
        textDecoration: 'none',
        display: 'block',
        fontSize: '1rem',
        fontWeight: 500,
        lineHeight: 1.6,
        letterSpacing: '0.0075em',
        opacity: 1,
        textTransform: 'none',
        minWidth: 0,
        padding: '10px',
        marginLeft: '10px',
        marginRight: '10px',
        '&:hover': {
            borderBottom: '2px solid mediumvioletred',
            background: '#8DB8DD',
            cursor: 'pointer',
            '&> div &:hover': {
                borderBottom: 'none',
            }
        },
    },
    navLinkStatic: {
        color: 'white',
        textDecoration: 'none',
        display: 'block',
        fontSize: '1rem',
        fontWeight: 500,
        lineHeight: 1.6,
        letterSpacing: '0.0075em',
        opacity: 1,
        textTransform: 'none',
        padding: '10px',
        marginLeft: '10px',
        marginRight: '10px',
    }
});

My attempt to convert .navLink:hover > div:hover {:

Things I have tried.


navLink: {

        '&:hover': {
            borderBottom: '2px solid mediumvioletred',
            background: '#8DB8DD',
            cursor: 'pointer',
            '&> div &:hover': {
                borderBottom: 'none',
            }
        },
        '&:hover > div:hover': {
            borderBottom: 'none'
        }

    },

Any assistance would be welcomed.

Answer №1

Make sure to use the correct syntax:

"&:hover > div:hover": { ... }
.

Check out this example that showcases the proper syntax:

import React from "react";
import ReactDOM from "react-dom";

import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  navlink: {
    border: "1px solid green",
    fontSize: "16pt",
    "&:hover": {
      backgroundColor: "lightgreen"
    },
    "&:hover > div:hover": {
      backgroundColor: "lightblue"
    }
  }
});
function App() {
  const classes = useStyles();
  return (
    <div className="App">
      <div className={classes.navlink}>
        Hello <div>CodeSandbox</div>
      </div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

https://codesandbox.io/s/nested-div-hover-yeri0?fontsize=14

You can also deeply nest with this alternative syntax:

const useStyles = makeStyles({
  navlink: {
    border: "1px solid green",
    fontSize: "16pt",
    "&:hover": {
      backgroundColor: "lightgreen",
      "& > div:hover": {
        backgroundColor: "lightblue"
      }
    }
  }
});

https://codesandbox.io/s/nested-div-hover-3ogmf?fontsize=14

For more information, take a look at the JSS documentation here: https://cssinjs.org/jss-plugin-nested/?v=v10.0.0-alpha.24

See also this related answer:

  • How do you change a style of a child when hovering over a parent using material-ui jss styles

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

Concealing Drawer Items in React Navigation 6

Is there a way to prevent certain screens from showing up as items in the drawer for @react-navigation/drawer version 6? In React Navigation 5, this could be accomplished by creating custom drawer content like the following: const CustomDrawerContent = (p ...

FirebaseError: The type 'Hc' was expected, but instead, a custom Yc object was provided

I've encountered an issue while attempting to perform a batch entry. The error I'm facing involves passing an array in a .doc file. Interestingly, this approach seems to work perfectly fine on another function where I pass an array into a .doc us ...

The localization feature is not functioning properly for the "Today" button within the LocalizationProvider of @mui/x-date-pickers

I'm having an issue with incorporating the "today" button from @mui/x-date-pickers into my app according to their documentation (here). The problem lies in the localization aspect. Even though I'm passing the "fr" adapterLocale to the Localizati ...

Im testing the creation of a global style using styled-components

Is there a way to create snapshot tests for styled-components with createGlobalStyle? The testing environment includes jest v22.4.4, styled-components v4.1.2, react v16.7, jest-styled-components v5.0.1, and react-test-renderer v16.6.3 Currently, the outp ...

How can I update my outdated manifest v2 code to manifest v3 for my Google Chrome Extension?

Currently, I am developing an extension and using a template from a previous YouTube video that is based on manifest v2. However, I am implementing manifest v3 in my extension. Can anyone guide me on how to update this specific piece of code? "backgro ...

The preflight response for CORS does not allow the header field content-type in .NET React

Seeking assistance with CORS implementation in React and .NET integration I have been struggling for a few days now trying to resolve the CORS issue in my React app when making POST requests to a basic .NET webAPI. The GET implementation works fine, but I ...

"Customize your Angular application by updating the background with a specified URL

Hello there, I've been attempting to modify the background URL once a button is clicked. In my CSS, I have the following default style set up. .whole-container { background: linear-gradient( rgba(0, 0, 0, 2.5), ...

issue with Firebase notifications not triggering in service worker for events (notification close and notification click)

I've been working on implementing web push notifications in my React app using Firebase. I've managed to display the notifications, but now I'm facing two challenges: 1. making the notification persist until interacted with (requireInteracti ...

Caution in material-ui version 4.0.1: Please ensure you have an element capable of holding a ref

After upgrading to material-ui v4.0.1, I noticed that Modals now require a forwarded ref, which has caused some issues for me when trying to implement a solution using class components and Dialogs. I attempted to use React.createRef() and React.forwardRef ...

Headerbar overlapping Div when scrolling

I'm currently trying to create a fixed header bar that allows the content of the page to scroll beneath it rather than displaying above it. This functionality is working on multiple pages, but I'm experiencing issues with my calendar page. When ...

Top and bottom labels with a line for navigating through steps - Material UI Stepper

I have been working on creating a stepper using Material UI (V5). Here is the code I currently have: import * as React from 'react'; import Box from '@mui/material/Box'; import Stepper from '@mui/material/Stepper'; import Step ...

Having trouble adjusting the size of a Font Awesome icon with React, Tailwind, and Next.js?

Struggling to adjust the size of a Font Awesome icon while learning React and Tailwind. Despite trying various options like size="sm" and h-px w-px in Tailwind, I can't seem to make any changes. Can anyone offer some assistance? Currently using Next. ...

Issue with React select not being updated properly after making changes to another related select field

Check out this code: https://codesandbox.io/s/inspiring-rhodes-jwv1zd?file=/src/App.js Steps to replicate the issue: Choose 'Fruits' from the first dropdown menu. Then select one of the fruits from the second dropdown menu. Now, change the fir ...

Using React to fetch data and then mapping it inside a function

I am facing an issue where I need to make a request for each item in the MAP, but I want to ensure that I wait for the response before moving on to the next object. Currently, my code is sending out all the requests simultaneously, causing the Backend to c ...

The Oracle Apex Login Interface with a Touch of Customized Styling

Currently, I'm working on creating a login page in Oracle APEX. While modifying the icon using CSS code, everything seems to be falling in place except for this one particular line: .t-Login-logo { background-image:url(#APP_FILES#LogoUpdated.jpg); bac ...

What could be causing the slow loading time of my Shopify App developed using Next.js (React)?

I recently followed a tutorial at However, I am facing severe performance issues with my app. It loads extremely slowly when changing tabs, whether it's running on ngrok, localhost, or deployed on app engine. I'm new to React, Next.js, and Shop ...

RouterContext Error: Invariant violation: Do not utilize <withRouter(App) /> in a context without a <Router> present

After wrapping my app with BrowserRouter and trying to export it as withRouter(App), I encountered the following error in the browser: 16 | return ( 17 | <RouterContext.Consumer> 18 | {context => { > 19 | invariant( | ^ ...

Tips on increasing the button size automatically as the elements inside the button grow in size

I have a button with an image and text inside, styled using CSS properties to achieve a specific look. However, I encountered an issue where the text overflows outside of the button when it's too long. I want to find a way to wrap the text inside the ...

Changing json into another format

I am struggling with a JSON data format issue. I have tried using Object.values and object.keys along with Array.prototype.map(), but my algorithm is not producing the desired outcome. [ { "2018-01-01": [ { "firstname": "mati", "lastname": "mati ...

Managing Input Fields in React Forms

Currently, I am working on coding a dynamic React form that presents a few challenges. My goal is to enable the printing of field values, update the state based on value changes in real-time as I type in the field, and display the state information in the ...