Using makeStyles() in MUI for conditional rendering

Trying to dynamically change the value of backgroundColor under the property "& + $track" using props.disabled but it seems that MUI does not recognize it. Why could that be?

const useStyles = makeStyles((theme) => ({
  root: {
    overflow: "visible",
    width: 36,
    height: 16,
    padding: 0,
    margin: theme.spacing(0.5),
    display: "flex",
  },
  switchBase: {
    padding: 2,
    color: theme.palette.grey[500],
    "&$checked": {
      transform: "translateX(18px)",
      color: theme.palette.common.white,
      "& + $track": {
        opacity: 1,
        backgroundColor: props => props.disabled ? theme.palette.grey[500] : theme.palette.primary.main,
        borderColor: theme.palette.primary.main,
      },
      "&:hover": {
        color: theme.palette.common.white,
      },
    },
    "&:hover": {
      color: theme.palette.primary.main,
    },
  },
  thumb: {
    width: 14,
    height: 14,
    boxShadow: "none",
  },
  track: {
    border: `1px solid ${theme.palette.grey[500]}`,
    borderRadius: 18 / 2,
    opacity: 1,
    backgroundColor: theme.palette.common.white,
  },
  checked: {
  },
}));

const StyledSwitch = (props) => {
  const classes = useStyles(props);
  return (
    <Switch
      classes={{
        root: classes.root,
        switchBase: classes.switchBase,
        input: classes.input,
        thumb: classes.thumb,
        track: classes.track,
        checked: classes.checked,
      }}
      {...props}
    />
  );
};

Answer №1

Props cannot be used inside makeStyles as it is not supported in that context. Instead, utilize the props.disabled variable in JSX to conditionally apply a class, and then define that class within makeStyles, specifying the background color there.

Alternatively, you can also make use of the Mui-Disabled class (a Pseudo-class applied to the internal SwitchBase component's disabled class).

"& + $track": {
    opacity: 1,
    backgroundColor: theme.palette.primary.main,
    borderColor: theme.palette.primary.main,
},    
"&.Mui-disabled + $track": {
    backgroundColor: theme.palette.grey[500],
},
 

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

"Taking cues from Instagram's web/desktop design, we have created

When you view someone's instagram page on a desktop or pc, the search bar is designed to float left when clicked, allowing text to be entered for searching. If no text is entered in the search field, the search icon and placeholder return to their ori ...

Shifting attention from the main point to the surrounding details (including siblings)

In my search bar layout, the main parent component consists of three child components - location dropdown, date picker (calendar), and duration dropdown. By default, the user's location is pre-selected in the location dropdown. I want the focus to shi ...

Is there a way for me to recreate the appearance of the outline and labeling found in Material-UI's outlined textfield?

Can anyone help me figure out how to hide the border behind the title text in an outlined textfield from Material-UI that I am trying to imitate? In the image below, you can see "Due Date/Time" taken from Material-UI library where the title hides the bord ...

Updating a table in Javascript after deleting a specific row

Is there a way to automatically reindex rows in a table after deleting a row? For example, if I delete row 1, can the remaining rows be reordered so that they are numbered sequentially? function reindexRows(tableID) { try { var t ...

Modifying the status of a link using jQuery

My ajax function handles two different outcomes based on the class of the link that is clicked. To avoid reloading the entire page when the link is clicked, I have utilized the following code: Everything seems to be working fine, however jQuery still rec ...

Using Node.js with the Instagram API resulted in the error message: "Failed to decode a text frame in UTF-8 format."

For my project, I am utilizing the Instagram API with the http node.js module. The API call is quite simple: getJSON : function(options, on_result, on_error) { var req = http.request(options, function(res) { var output = ''; ...

Is there a more efficient method to tally specific elements in a sparse array?

Review the TypeScript code snippet below: const myArray: Array<string> = new Array(); myArray[5] = 'hello'; myArray[7] = 'world'; const len = myArray.length; let totalLen = 0; myArray.forEach( arr => totalLen++); console.log(& ...

How can I reposition an image diagonally to a specific location using JavaScript in p5.js? Is there a method to display an image and then conceal it at a chosen location in p5.js?

Is there a way to move the third image diagonally until it intersects with the two images? var pic1; var pic2; var pic3; let posX=0 let posY=0 const rightwall=350; function preload(){ pic1=loadImage("5.png") pic2=loadImage("iron.jpg&qu ...

Issue: Unable to set headers after they have been sent while using express-fileupload in the application

app.post('/profile', function(req, res) { // save file if (req.files) { let sampleFile = req.files.sampleFile; sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) { if (err) ...

Swapping out pages with JSON outcomes is a common practice when utilizing ASP.Net MVC in conjunction with JQuery Ajax

When making an ajax call to update an entity and returning the success state in the MVC controller, I encountered a problem that resulted in the page changing with the URL becoming that of the MVC controller action and displaying the JSON result as content ...

Tips for incorporating theme colors in the "color" prop when employing MaterialUI components

Trying to utilize the colors from my Mui palette as values for the color property in this way: For example: <Tabs indicatorColor="primary.mainGradient" > <Tab /> </Tabs> However, this approach does not seem to wo ...

The sidebar in Semantic UI does not have a specified height for the form segment

Need help troubleshooting a button that slides out a vertical sidebar. I want to include a short form for users to input search queries within the sidebar. The issue seems to be with the heights of #search-sidebar and .ui.form.segment. Here is the code s ...

Avoid cascading of the 'display' property in JavaScript styling to prevent inheritance

Is there a way in Javascript to toggle the visibility of a larger portion of HTML without affecting inner display properties with display: <value>? Despite setting an outer display property using Javascript, the inner display properties are also alt ...

Ways to create an oval background for my button

Can someone help me create a button with a unique shape similar to the Products button on stack overflow? Check out this image for reference I attempted using border radius, but it didn't give me the desired effect. I searched for other options but c ...

Using Ajax without implementing JavaScript

Is it possible to develop an application that utilizes Ajax without relying on JavaScript, allowing it to function even if JavaScript is disabled by the user in their browser? Are there any restrictions or limitations to consider? ...

Issue arising during reconnection following a disconnection in the node-redis client

I'm struggling to understand why the SocketClosedUnexpectedlyError error is being triggered in the code snippet below: const redisClient = require('redis').createClient(); redisClient.connect().then(function() { return redisClient.disconn ...

Challenges with pjax/ajax and handling the browser's back button

I've implemented pjax to ajaxify my menu links, which works well until I encounter an issue with the browser back button. In my JavaScript file, I have both Common Script files (to load all necessary js files when the user hits the URL) and Script fil ...

Deleting the first element of an array in JavaScript using Node.js

I'm struggling to remove the first element of an array. When I try to use slice(1,1) or shift, I can't seem to retain a list. For instance, my array: [1499783769720,"54:52:00:62:46:66","54:52:00:b0:fa:57","54:52:00:8f:d9:7c","54:52:00:e7:67:10" ...

The error code TS2554 is triggered when 5 arguments are passed instead of the expected 3-4

I'm utilizing the gsap plugin to craft a captivating text animation effect. As I reached the last line of code in my 'animation_text_1' function, specifically where it states "TweenMax.staggerFromTo(.....)", an error cropped up which read: ...

I'm looking for a way to retrieve an object from a select element using AngularJS. Can

I am working with a select HTML element that looks like this: <select required="" ng-model="studentGroup"> <option value="" selected="">--select group--</option> <option value="1">java 15-1</option> <option value="2">ja ...