Can a specific CSS rule be written in Material UI using makeStyles that will only apply if the element has both classes together?

It's common knowledge that achieving this in CSS is a possibility.

.makeStyles-mainNavWrapper-67.sticky{
  position: fixed;
  top: 0px;
  opacity: 1;
  transition: opacity 1s ease;
  padding: 10px;
}

I am curious to find out if this can be achieved in Material-UI as well, eliminating the need for separate stylesheets (one for the MaterialUI ReactApp and one linked in the HTML tag).

const Header = (props) => {
  const useStyles = makeStyles(theme => ({
    mainNav: {
      zIndex: '3',
      color: 'white',
      textAlign: 'right',
      marginRight: '10%'
    },
    mainNavWrapper: {
      paddingTop: '2%',
      background: 'rgba(0,0,0,0.8)'
    },
    mainNavWrapper.sticky: {
       I've attempted to combine two classes in MaterialUI with no success. Is there a way to accomplish this?
    },

My attempt at concatenating two classes in MaterialUI resulted in errors.

Answer №1

After much searching, I finally discovered the solution. By importing the react-jss package and carefully following their documentation, I was able to unlock the power of jssNested syntax. This allowed me to access nested elements and define rules that only activate when two specific classes are attached to an element.

Here is the implementation:

import React from 'react'
import { render } from 'react-dom'
// Import React-JSS
import injectSheet from 'react-jss'

// Define Styles using JSS format
const styles = {
  mainNav: {
    // Main Navigation styles here
  },
  li: {
    // List item styles here
  },
  mainNavWrapper: {
    // Main Navigation Wrapper styles here
  },
  myLabel: {
    // Label styles here
  }
}

// Create a component Button using the defined styles and pass it the 'classes' prop.
const Button = ({ classes, children }) => (
  <div className={classes.mainNavWrapper}>

    <nav className={classes.mainNav}>
      <ul className={classes.ul}>
        // List items with applied classes and links here
      </ul>
    </nav>
  </div>
)

// Inject the stylesheet into the component for styling
const Test = injectSheet(styles)(Button)

export default Test;

Answer №2

I believe I may have stumbled upon the solution after some thorough rubberducking.

https://github.com/cssinjs/jss-nested

const styles = {
  container: {
    padding: 20,
    '&:hover': {
      background: 'blue'
    },
    // Including a global .clear class in the container.
    '&.clear': {
      clear: 'both'
    },
    // Referring to a global .button within the container.
    '& .button': {
      background: 'red'
    },
    // Utilizing multiple container references in one selector
    '&.selected, &.active': {
      border: '1px solid red'
    }
  }
}

translates to:

.container-3775999496 {
  padding: 20px;
}
.container-3775999496:hover {
  background: blue;
}
.container-3775999496.clear {
  clear: both;
}
.container-3775999496 .button {
  background: red;
}
.container-3775999496.selected, .container-3775999496.active {
  border: 1px solid red;
}

Some of my other code is currently not functioning properly so it will require some time to validate this.

Answer №3

I decided to keep the previous answer because it demonstrates how to resolve this problem using react-jss. The same solution can be achieved with makeStyles in MaterialUI. It seems like there was a syntax error somewhere that prevented my css rules from taking effect.

Here is the code using makeStyles, with some breakpoint code included:

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

const Header = () => {

  const useStyles = makeStyles(theme => ({
    root: {
      padding: theme.spacing(1),
      [theme.breakpoints.down('sm')]: {
        backgroundColor: 'red',
      },
      [theme.breakpoints.up('md')]: {
        backgroundColor: 'blue',
      },
      [theme.breakpoints.up('lg')]: {
        backgroundColor: 'green',
      },
    },
    mainNav: {
      zIndex: '3',
      color: 'white',
      textAlign: 'right',
      marginRight: '10%',
      '& ul': {
        zIndex: '2',
        textAlign: 'right',
        listStyleType: 'none',
        margin: '0px',
      }
    },
    li: {
      display: 'inline-block',
      marginLeft: '3%',
      '& a': {
        color: 'white',
        textDecoration: 'none',
        marginRight: '10px',
        padding: '10px',
        '&:hover': {
          background: '#3498db'
        }
      }
    },
    mainNavWrapper: {
      background: 'rgba(0,0,0,1)',
      width: '100%',
      opacity: '1',
      transition: 'width 2s ease',
      padding: '10px',
      position: 'fixed',
      zIndex: 1,
      '& .sticky': {
        position: 'fixed',
        top: '0px',
        opacity: '1',
        transition: 'opacity 2s ease',
        padding: '10px',
        zIndex: 1
      },
      '& .scrolling': {
        opacity: '0',
        position: 'fixed',
        transition: 'opacity 30ms ease'
      }
    },
...
inside the functional component's return ():
 <div className={classes.root}>

      <div className={classes.mainNavWrapper}>

        <nav className={classes.mainNav}>
          <ul className={classes.ul}>
            <li className={classes.li}><a href="#" >home</a></li>
            <li className={classes.li}><a href="#">about us</a></li>
            <li className={classes.li}><a href="#">packages</a></li>
            <li className={classes.li}><a href="#">reviews</a></li>
            <li className={classes.li}><a href="#" className={classes.current}>contact us</a></li>
          </ul>
        </nav>

      </div>
</div>

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

Using jQuery to access the ID of a div and create a custom close button

I am trying to implement a close button for my popup DIVs. Each one has a unique ID and I want to hide them by setting the CSS 'display' property to 'none' when closed. However, the following example is not functioning as expected. I a ...

In a jQuery project, WebStorm marks all $-operators as "unrecognized."

Just a quick question from a beginner: I'm facing an issue where my WebStorm IDE doesn't recognize any jQuery code, even though the webpage functions correctly in the browser. Here's what I've done so far: I have installed WebStorm V ...

The state in Reactjs is not displaying as expected

Check out my ReactJS todo app that I created. However, I am facing an issue with deleting todos. Currently, it always deletes the last todo item instead of the one I click on. For example, when trying to remove 'Buy socks', it actually deletes ...

Express js is unable to retrieve the page at /page

I'm facing a persistent routing error on express.js. Despite multiple attempts to fix it by referring to the documentation and making changes, I'm still stuck. Here's the basic content of the link pointing to the '/sell' route: i ...

To ensure proper formatting, I must include a comma operator for numbers while typing and limit the decimal places to two

Could someone assist me in formatting a number to include commas and restrict the decimal places to two using regex? I have attempted the following, but need help making it work properly. Currently, when I enter a number it shows up as 1231244, however I ...

When the dependencies change, useEffect is not triggered

import React, { useState, useEffect, useRef } from "react"; import ReactDOM from "react-dom"; import "./styles.css"; function App() { const [minus, setMinus] = useState(3); const ref = useRef(null); const handleClick ...

Changes to the theme state will only trigger a single rerender within the ThemeProvider

I am new to ReactJs and I'm trying to create a feature where the theme changes when a button is clicked. However, I am facing an issue where the theme changes only once on clicking the button, subsequent clicks have no effect. class App extends React. ...

What specific width range would be best for my needs?

I used to have the default font style of Myriad Pro Light and a padding setting for my main menu on my website as follows: .menu > li > a { padding: 17px 15px 15px 15px; } Recently, I changed the default font style to Montserrat. However, this chang ...

Guide on keeping your MongoDB collection up-to-date with Mongoose

I'm currently facing an issue while working on a project. My goal is to build a MongoDB database where I can store dates and YouTube video links. I've chosen to use Mongoose as my ORM. The problem I'm encountering is that while I can create ...

Script tag for Next.js reloading functionality

I have been facing a challenge while trying to integrate third-party commenting scripts like (disqus, remark42, hyvor) into my next.js application. The issue I encountered is that the script only loads on the initial page load. Subsequently, I need to refr ...

Validation for dates in Angular.Js input is important to ensure that only

Take a look at this form: <form name="user_submission" novalidate="novalidate" method="post"> <input type="date" name="date_of_birth" ng-focus="save_data()" ng-model-options="{timezone: 'UTC'}" ng-pattern="/^(19\d{2}|[2-9]& ...

Personalized scrollbar extends beyond the screen

I have been working on creating my own scroll bar, and for the most part, it's functioning well. However, there is one small issue that I'm facing. Whenever I reach the bottom of the page, the handle of the scroll bar disappears underneath the v ...

Display unique information according to the value in the form field (email domain)

I've developed an innovative ajax signup form that integrates jQuery and CSS3. The unique feature of this form is its multi-step process. In the first step, users are required to enter their email address and password. What sets this form apart is i ...

React application is experiencing issues with environment variables

Having some trouble with a third-party API and the API key I'm trying to store in a .env file. Despite my efforts, every time I attempt to access it using process.env, it shows up as undefined. The .env file I'm using is named keys.env and is lo ...

Executing javascript after an AJAX call within an on() method: Tips and tricks

I am struggling to make a $.ajax() call within a function triggered by the .on() method, in order to execute a script on a .click() event after updating newly appended data. I have tried numerous times to troubleshoot, but I can't seem to pinpoint the ...

Issue with page break functionality during print preview

div.pagebreak { page-break-after: always; page-break-inside: avoid; } HTML <!-- Page separator --> <div class="pagebreak" style="float: none;"><hr class="hidden-print" /></div> <app-mud-chec ...

The offcanvas close button fails to function if initialized through JavaScript

I have integrated offcanvas into the page layout. By default, it remains hidden but I want it to be visible at all times on large screens. On smaller screens, there should be a button to dismiss it, as well as another button in the menu panel to show the o ...

Adding additional properties to Material UI shadows in Typescript is a simple process that can enhance the visual

https://i.stack.imgur.com/9aI0F.pngI'm currently attempting to modify the Material UI types for shadows, but encountering the following error when implementing it in my code. There is no element at index 25 in the tuple type Shadows of length 25. I&a ...

Issue with installing node-sass via npm install and node-gyp

I've encountered an issue related to the node-gyp and node-sass. After updating my npm from version 6 to 8.19.4, I started facing errors during the npm install process, which used to work fine with version 6. The specific error message I'm seein ...

Guide on integrating msw with Next.js version 13.2.1 (Issue: Unable to access worker.start on the server)

I'm currently in the process of integrating a simulated API that sends back a response object containing a series of messages meant to be displayed in the UI (specifically, a chatbox) alongside the username, user picture, and other relevant informatio ...