The Mui Switch track color fails to change when checked

I'm looking to customize the colors of the track for both checked and unchecked states. Currently, the track color is working for the unchecked state but defaults for the checked state:

Checked State:

https://i.stack.imgur.com/eGV4a.png

Unchecked State:

https://i.stack.imgur.com/qn1M1.png

import Switch from '@mui/material/Switch';

<Switch
  sx={{
    ".MuiSwitch-thumb": {
      backgroundColor: "#FF9528"
    },
    ".MuiSwitch-track": {
      backgroundColor: "#FF4823"
    },
    "& .Mui-checked": {
      ".MuiSwitch-thumb": {
        backgroundColor: "#FF4823"
      },
      ".MuiSwitch-track": {
        backgroundColor: "#FF4823"
      }
    }
  }}
/>

Answer №1

You're almost there.

In the Customize section of the MUI documentation, they provide an example where the checked version of the track requires a CSS selector of +, so instead of just .MuiSwitch-track, it should be +.MuiSwitch-track.

UPDATE

The default style is overriding the checked version, so we need to modify the CSS selector slightly to give our custom styling higher priority. I fixed it following the official documentation's guidance.

  <Switch
    sx={{
      ".MuiSwitch-thumb": {
        backgroundColor: "#FF9528"
      },
      ".MuiSwitch-track": {
        backgroundColor: "#FF4823"
      },
      "& .MuiSwitch-switchBase": {
        "&.Mui-checked": {
          "+ .MuiSwitch-track": {
            backgroundColor: "#FF4823"
          },
          ".MuiSwitch-thumb": {
            backgroundColor: "#FF4823"
          }
        }
      }
    }}
  />

Find the code example in the MUI doc here -- https://mui.com/material-ui/react-switch/#customization

Check out a demo on CodeSandbox with your code https://codesandbox.io/s/sad-jasper-5vqjgn?file=/src/App.tsx

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 Node JS to serve an HTML file along with cascading style sheets

As I delve into pure node.js, I encountered an issue related to the HTTP protocol. After spending hours searching and testing my code, I finally managed to serve my HTML page with CSS successfully. Take a look at my code snippet below: const server = http ...

Working with a Mix of Properties in Styled Components

Incorporating a button component with material design using styled-components is my current task. This component will possess various props including size, icon, floating, etc. However, managing the numerous combinations of props has become quite overwhel ...

PHP and mysqli combine to create a versatile image slider with changing images

I am looking to implement an image slider that can be updated by the admin using php and mysqli. The admin should have the ability to easily add or remove images as needed. ...

Maintain hook varieties during implementation of array deconstruction

I have been developing a straightforward hook to export animation helper and element reference. import { gsap } from 'gsap'; import { useRef } from 'react'; export function useTween<R extends gsap.TweenTarget>(vars: gsap.TweenVar ...

Retrieving data from Firebase query and displaying as an array of results

Currently utilizing the @react-native-firebase wrapper for interaction with Firebase's Firestore. Within my function, some querying to a specific collection is performed, with the expected result being an Array object containing each located document. ...

Tips for successfully passing a variable in Gatsby's GraphQL system

I am trying to display multiple images using the relative path of each image that is passed as a prop to the component. Below is my code snippet: import Img from "gatsby-image"; import {useStaticQuery, graphql } from "gatsby"; const Tea ...

Dispatch prop within useEffect

App.js -> <Lobbies inGame={inGame} setLobby={setLobby} userName={userName} userKey={userKey}/> Lobbies.js -> import React, { useState, useEffect } from 'react'; import firebase from 'firebase'; const Lobby = ({userKey, ...

Troubleshooting error in Next.js when adding "sizes" attribute to Image component with layout set to "responsive"

When you use the following code: <Image src="/images/lorem.jpg" height={150} width={850} layout="responsive" sizes="50vw" // <== ...

What causes the sudden change in value of this array?

I can't seem to figure out what's going on with this question. It might be something silly, but I haven't been able to find any clues. Here is the array in question: const superVillains = [ { value: '1', label: 'Thanos&apo ...

Is it advisable to incorporate Material-UI into a React project?

When it comes to designing a login page in react, I stumbled upon material-ui. The real question is, should we utilize Material-UI for this purpose? Furthermore, how can we manage styles in a separate file in the given examples? It seems logical to place t ...

Unable to properly update value with window.setInterval, useEffect, and useState functions

In this scenario, I am creating a simulation of a timer with a model result that is dependent on the timer value. The goal is to update the timer while simultaneously changing the model value every second. "use client"; import { useState, useEff ...

The jQuery append function does not incorporate CSS styling

I am currently facing an issue where my jQuery code successfully appends a piece of HTML, but the CSS styles are not being applied to it after the append operation. What is the correct approach to resolve this? This is the method I am using: if(listone[ ...

What is the best way to merge two AngularJS form validation directives criteria using CSS?

When both $dirty and $invalid are true, I would like the input fields to have a red background. However, I am only able to do this one by one, which is not ideal. input.ng-dirty && input.ng-invalid { background-color: red; } ...

What is the best way to use jQuery to emphasize specific choices within an HTML select element?

Seeking help with jQuery and RegEx in JavaScript for selecting specific options in an HTML select list. var ddl = $($get('<%= someddl.ClientID %>')); Is there a way to utilize the .each() function for this task? For Instance: <select i ...

Vertical Divider in Material UI Grid not displaying properly

I've been experimenting with adding a vertical <divider> to a grid layout, but it's not showing up. If I remove it from the <Grid Item>, it displays properly, but I know that's not the right way to do it. What am I missing here? ...

How about a CSS one-by-one black pixel that's not opaque?

I've been attempting to achieve a 70% transparent black background on an element, but unfortunately, I had to use a pixel to address browser compatibility problems. Using CSS alone would make the entire content of the element transparent as well. Her ...

Steps for automatically retrying a failed expect statement in Jest

In my React application, I am utilizing Jest for performing unit testing. One aspect of my application involves a Material UI date picker with next and previous buttons. The selected date is displayed in the browser URL. Each time the user clicks on the ne ...

Utilizing Bootstrap CSS within Vue's scope

I'm attempting to integrate Bootstrap into a Vue component while ensuring that all CSS is scoped. My initial approach was as follows: <style scoped> @import "~bootstrap/dist/css/bootstrap.css"; @import "~bootstrap-vue/dist/bootstrap-vue.css"; & ...

Ways to heighten the `RadComboBox` `DropDownHeight` featuring `Templates`

One of the challenges I'm facing involves a RadComboBox setup like this: <telerik:RadComboBox ID="RadComboBoxNames" runat="server" Width="470px" DropDownAutoWidth="Enabled" MaxHeight="363px" Skin="MySkin" EmptyMessage="Select" High ...

Prevent backspace and delete keys from functioning in a column of a DataGrid using material-ui

Does anyone have a solution for disabling the backspace and delete keys in a column when using DataGrid with material-ui? ...