What exactly is the purpose of the double ampersand selector, '&&', when it comes to overriding the root class with makeStyles within Material-UI React?

I recently started using Material-UI and encountered an issue where I couldn't override the root class for Avatar, specifically MuiAvatar-root.

Material-Ui Version: 4.11.3

Despite following examples provided by material-ui's documentation here, I was unable to successfully override the Avatar style.

In the code snippet below

1st

<Grid item>
    <Avatar alt="avatar" src={avatar} classes={{root: classes.root }} />
</Grid>

The above approach didn't yield any results along with several other methods attempted.

root: {
    width: "128px",
    height: "128px",
    margin: "8px",
},

Eventually, I managed to override the Avatar style by utilizing the overrides key in my global theme styles as shown below:

const theme = createMuiTheme({
  // Not Required
  overrides: {
    MuiAvatar: {
      root: {
        width: "128px",
        height: "128px",
        margin: "8px",
      },
    }
  },
  palette: { 
   ...
});

However, this method led to unintended changes in all Avatars across my project. An example is demonstrated below:
2nd

<Container className={classes.center}>
    <Avatar className={ classes.avatar }>
        <ContactMailIcon />
    </Avatar>
</Container>
const useStyles = makeStyles((theme) => ({
  ...
}));

To resolve the issue, I discovered that adding '&&' before the style properties helped in both scenarios as illustrated below:

For 1st scenario

root: {
        '&&': {
            width: "128px",
            height: "128px",
            margin: "8px",
        }
    },

And for the 2nd scenario:

export const useContactStyles = makeStyles((theme) => ({
    ...
    avatar: {
        "&&": {
            margin: theme.spacing(1),
            backgroundColor: "#ff4838",
            alignItems: 'center',
        }
    },
    ...
}));

This workaround successfully allowed me to override the default MuiAvatar-root class and apply individual styles. However, I am uncertain about the functioning of '&&' or its relevance to SASS which I have no prior experience with.

EDIT

**Upon further explanation from @Bassem and through this article, it seems that '&&' is used to increase specificity/priority in styling.

Although this trick resolved my issue without causing conflicts, I am curious whether this method is recommended practice or if there are potential drawbacks to using '&&'?

Answer №1

To successfully apply the classes, you will need to utilize the makeStyles utility in this manner:

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

const useStyles = makeStyles((theme) => ({
  root: {
    width: "128px",
    height: "128px",
    margin: theme.spacing(1),
  }
}));

export default function App() {
  const classes = useStyles();
  return (
      <Avatar classes={{ root: classes.root }} />
  );
}

You can see a live demonstration here: https://codesandbox.io/s/friendly-chatterjee-w507i


Typically, using the double ampersand syntax to customize Material UI's components is not recommended. However, it can be used to increase the specificity if needed. For more information on this technique, check out this informative article: https://dev.to/magischerzwerg/double-ampersand-trick-in-sass-with-react-4khe

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

Error in JavaFX: CSS Parser anticipating COLON

Encountered an error and struggling to find the issue as everything seems right from my perspective: CSS Code: @font-face { font-family: 'Titillium'; font-style: normal; font-weight: normal; src: url('Titillium.ttf'); ...

I am attempting to set up React, but I keep encountering an issue that says 'Error: EPERM: operation not allowed'

My attempts to set up React have been unsuccessful so far. Initially, I tried installing it using the command npx create-react-app ./, which did not work. Then, I attempted to run npm init react-app my-app, but unfortunately, that also failed. The error me ...

What is the best way to integrate React and Node.js in a single project?

Recently, I have run into a minor issue. I am aware that I can build a react-app using npm run build to create an optimized build folder for production use. However, after incorporating node.js into my react application some days ago, I am now uncertain ab ...

The images on the Shopify platform are becoming increasingly fuzzy

I'm facing an issue where the images I add to my Shopify site using the Brooklyn theme appear blurry unless resized to a small scale. The dimensions of the images are 1748 x 1240 at 300dpi. My intention is to implement a JQuery image slider (lightsli ...

Tips for troubleshooting the error message "is not a function" in a React application

Hi there, I'm currently delving into learning React and have encountered an issue that says: (TypeError: newsData.map is not a function) in my browser when running my code. Oddly enough, Visual Studio Code doesn't flag any errors, only Chrome doe ...

Using the Strikethrough Feature in React

Is it possible to apply a strikethrough effect to a checkbox's label text when toggled on and off? In my system development process, I've utilized various methods. What modifications should be made in the fComplete method for this feature to wor ...

Customizing the underlineFocusStyle of a material-ui TextField component using regular CSS styling

When working with Material-UI components, you have the option to provide a style object for the component itself within the JSX tag. However, in certain cases like the underlineFocusStyle of a TextField component, you need to use a separate style object. ...

Leveraging Hooks in React to develop components

I have been experimenting with using a hook to create a textbox that includes the state value as part of the hook. However, I have been encountering an issue where the textbox loses focus whenever I try to type. To better illustrate what I am facing, ple ...

What could be causing my <UL> to not properly expand around the <LI> items inside of it?

I am currently working with WordPress and have created a menu using a list structure. Here is an example of how it looks: <ul> <li>Home</li> <li>About</li> <li>ParentItem <ul> <--- The heig ...

Unexpected behavior in React-Native when filtering array objects

I am currently working on a react-native project where I am dealing with an array object that is being fetched from the backend. Here is a snippet of the Array. { "2010":[ { "id":1243, "eventName": ...

What are some strategies to prevent visual glitches while moving between screens in React Native Expo?

Currently, I am working on implementing a sign-in screen and a create account screen for my application. These screens have buttons that allow users to navigate back and forth between them. While each screen functions correctly individually, there is somet ...

Can CSS3 be utilized to craft this specific shape?

Can CSS3 be used to create the shape I need? I came across this website http://css-tricks.com/examples/ShapesOfCSS/, but I am unsure if any of the shapes on that page can be customized to match the specific shape I have in mind. Thank you! ...

What could be causing the issue with absolute positioning not functioning correctly?

I'm having trouble keeping my footer at the bottom of the page: body, html{position:relative;} footer{position:absolute;} Even when I use bottom: 0;, the footer doesn't seem to go all the way to the bottom. Is there anyone who can help me troub ...

React will not adjust the height of the main component when the length of the child component changes

Having an issue with the height of my website. Although my component has height: 100vh; defined, there is a scenario where the child component extends beyond the viewport but the height remains unchanged, causing the component to fall below the white back ...

Opening Shared Popper takes two clicks to activate again

Each button represents a different sports category. When clicked, a Popper opens with the corresponding sports content. The issue is that once the Popper is open for one sport, it takes two clicks to switch to another sport - one click to close the curre ...

The Express server is failing to establish a connection with Node.js due to an error in the

import React, { useState, useRef, useEffect } from 'react' import user from '../components/Client'; import Editor from '../components/Editor'; import { initSocket } from '../socket'; import ACTIONS from '../acti ...

The React application is unable to communicate with my Express application in a production environment, despite functioning properly during development

Currently, I am attempting to make a basic get request to my express backend located at mywebsite.com/test. The expected response from the server should be {"test": "test"}. While this is working perfectly fine in development on localho ...

How can I select just one element to be impacted by a click event when using map in TypeScript?

Currently, I'm facing an issue where I want to change the icon of a button when it's selected. The problem is that using map affects all buttons even if only one is selected. // ... const [clicked, setClicked] = useState(false); <Button sta ...

I'm at a loss with this useState error, can't seem to figure

Could you please help me understand what is incorrect in this code snippet? import React, { useState } from 'react'; import UsrInput from '../component/UsrInput' import TodoItemList from '../component/TodoItemList' const ...

Using JQuery to eliminate the current div in an image slider

I currently have an image slider that allows users to switch between images. There are two buttons - one adds a new item to the slider, while the other is supposed to remove the current image from the slider, but it doesn't seem to be working properly ...