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

Label for the checkbox is covering other content on the screen in 1024 x 768

Here is the JSP code snippet: <h:field path="configuredChannels" required="true" code="admin.menu.channels"> <div class="row-fluid" data-channel-checkboxes="#"> <form:checkboxes element="div class=&apos ...

The margin-right and margin-left properties function differently when it comes to dealing with overflow of floated divs

<body> <div class="content"> <div class="content-sidebar"> content-sidebar </div> <div class="content-main"> content-main </div> ...

Adjust the label width to ensure that it aligns correctly with the outlined input field

My current issue involves using a `TextField` with a lengthy label. Despite the label having enough space for the text, it tends to jump to the next line. Check out my codesandbox It seems like the automatic calculation is incorrect, so I am considering ...

Rendering on the client side

When using a server-side (.net app) application, only the necessary page is loaded to the client. However, in Client-Server applications (ReactJS + WebService), all pages are loaded on the client side. Does this initial load impact performance? ...

Aligning UL LI elements vertically for multi-line textORHow to vertically

I am dealing with a ul list that contains both single and multi-line li text. The issue is that the second line of the multi-line text starts at a different indentation than the first line. I need a simple solution to resolve this problem that works seaml ...

Utilize the class names to assign a distinctive color using mixins in SCSS

I am diving into the world of Sass and I have a peculiar challenge. I want to create a class that allows me to set a color using percentages for red, green, and blue values. For example, the class name color-50-10-60 would represent 50% red, 10% green, a ...

Trouble arises with Pagination feature of Mui Data Table

Currently, I am working on a project that involves retrieving data from the CoinMarketCap API and presenting it in an MUI Data Table (specifically a StickyHeader Data Table). However, I have been encountering difficulties with changing the color of the tex ...

Optimizing performance when rendering a long list of Reactjs components is a challenge

I have a dedicated page that displays a lengthy list of tags, typically containing between 10,000 and 20,000 tags. To render these tags, I utilize the following component: render() { return ( <div> {this.state.tags.map((tag, i ...

Eliminate the CSS triggered by a mouse click

Having some difficulty toggling the switch to change the background color. Struggling with removing the applied CSS and getting it to toggle between two different colored backgrounds. Code Sample: <!Doctype html> <html lang="en"> <head> ...

Is there a way to shift this div to the bottom and incorporate some quirky pop-up squares?

I am struggling to figure out how to move this div to the bottom. Additionally, I want to create temporary pop-up squares (simple divs) in random directions that will disappear after 50ms. My attempt to float this box to the bottom did not yield the desir ...

Can I trust the security of my credentials if they are able to be logged in the console

While working with NextJS, I've encountered a challenge in applying server-side rendering methods like getStaticProps to maintain credentials on the server rather than exposing them to the client. Despite my attempts, I couldn't find a straightfo ...

How to keep React Material UI Tooltip open on hover of List items?

In my project, I'm using Material UI to create a dynamic list of users. Each user is displayed as a ListItem with their profile image, and when hovering over the image, I want a tooltip to show up with additional user information. Although the basic ...

Having divs stacked on top of each other with one positioned fixed and the other

In my HTML document, there is a main div element called container that contains several child elements also in the form of divs. One specific child div, named top_bar, has its positioning set to fixed, while the rest of the child divs have relative posit ...

Is the textarea's shape out of the ordinary?

Most textareas are typically rectangular or square in shape, similar to this: However, I am interested in having a custom-shaped textarea, like the example below: Is it feasible to achieve? ...

What steps can I take to resolve the hydration issue with the authenticating component?

My current setup involves an authentication component that verifies whether the user has a token stored in local storage. Below is a snippet of the code: import { useRouter } from "next/router"; import { useState } from "react"; const ...

What is the best way to adjust the placement of this object so it is anchored to the left side?

I'm struggling to position one of my divs more to the left within a flex container. No matter what I try, changing the class of the div doesn't seem to have any effect. Here's the code snippet: import React from 'react' import &apo ...

Troubleshooting issues with the sidebar navigation in Laravel project using Vue and AdminLTE

I successfully installed AminLte v3 via npm in my Laravel + vue project and everything is functioning properly. However, I am facing an issue when I attempt to click on the main menu item in the Side navbar that is labeled as <li class="nav-item has-tr ...

Send a changing value to a more advanced component

I have encountered a situation in my code where I need to reuse the same lines of code in multiple places. This seems like the perfect opportunity to extract this code into a base class. After researching about Higher-Order Components, I attempted to imple ...

Designing a unique customized top navigation bar in Magento 1.9.2

I recently attempted to create a unique top menu in magento 1.9.2 by modifying the Navigation.php file located at app/code/core/Mage/catalog/Block/. I added some custom classes in an effort to customize the menu. In order to achieve this customization, I ...

What would be more efficient: inputting all items in a form at once or adding them one by one consecutively

My mind is preoccupied with a dilemma: is it better to have all possible items already on the form, or should items only be added when the user requests them? Let me elaborate - Imagine I have a form with 4 input fields and one textarea. Alongside that, t ...