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

What is the best way to conceal the jqgrid entirely while it is still loading?

Having an issue with my jqgrid. As I load the table and fetch a large amount of data from the database, the loading process naturally takes a few seconds. However, during this time, I can see the column headers without any rows or styles applied to the jqg ...

Restore title to original metadata value following dynamic modification

Within my Next.js project, I have implemented a feature that updates the page title dynamically based on a specific event: if (unread_count === 0) { document.title = "Flow Chat"; } else { document.title = `Flow Chat - ${unread_count} unread m ...

Retrieving a parameter in NextJS from the request.body when it is not found

In the API code for my nextJS, I have implemented the following logic: export default async function handler(request, response) { if (request.method === "POST") { const type = request.body.type ?? 'body type' const ...

Format six images in a horizontal row for desktop and ensure they resize appropriately for mobile viewing

I am looking to arrange images of different sizes in rows depending on the device orientation. For desktop, I want 6 images with proper margins, 2 images in a line for portrait, and 4 images for landscape orientation. Any extra images should be placed in a ...

"Explore the versatility of React Day Picker with customizable months and weekdays_long

I have implemented the following packages: "react": "^18.2.0", "react-day-picker": "^8.1.0", and I am attempting to translate the months and days into French. However, despite passing the translated arrays to my < ...

What is the best way to justify list items to the left?

Having trouble aligning my list content to the left. Any suggestions are welcome! Here is a snippet of the code: <div class="col-md-4 mb-1"> <i class="fas fa-hiking fa-4x"></i> <h4 class="my-4" font-weight-bold&g ...

Is it possible to utilize JSX independently of React for embedding HTML within a script?

Is it possible to incorporate inline HTML within a script using a library such as jsx? <script src="jsx-transform.js"></script> <script type="text/jsx"> define('component', function () { return (<div>test html code< ...

Ensure that the text on the button is aligned to the right and is positioned directly

Looking to adjust the alignment of the menu icon on the left side of the menu text. Unsure about the best approach with my current CSS - should I utilize a grid layout to separate them on one side each, or perhaps use flexbox to align them inline? Below i ...

Navigate to a local server running on localhost:3000 and access the external URL www.google.com

When attempting to access an external URL, the website that should open in a new tab is redirecting to http://localhost:3001/www.google.com instead of www.google.com. <IconButton key={index} size="large" color="primary" href={e.url ...

Error encountered when referencing prop on textarea: 'There is no suitable overload for this call'

I've been referring to the documentation in order to set a reference using the useRef hook, with the goal of being able to programmatically clear an input field. However, when I add ref as a prop to a textarea, it triggers a lint error saying that no ...

Extract the Floating Number and Set as Fixed Decimal with Zero Decimal Places

I have a react-native code snippet that I'd like to modify. <Grid item xs={12} sm={12} md={12} lg={12} style={{textAlign:isRTL==='rtl'?'right':'left'}}> <Typography color={'primary'} style={{fo ...

Tips on adjusting CSS code to ensure that a single accordion panel is open when the page first loads

I have a code that is functioning perfectly. However, I need to make a modification so that there is a default panel open when the page loads or refreshes. #acc-label { display: block; float: left; height: 330px; width: 50px; margin-bottom: 10px ...

Utilizing multiple modals in ReactJS

I recently joined this platform and came across some related answers that use different packages and class components. However, I have a functional component and am utilizing MUI Dialog for popups. The current functionality only caters to one modal, but I ...

Leveraging the power of ReactJS for efficiency in executing multiple API calls concurrently

I'm encountering an issue with the following code snippet: let tmpContributors = [...this.state.contributors]; for (let i = 0; i < 10; i++) {//10 most active contributors due to performance and github limits contributorPropertiesPromises.pus ...

Save calendar events by dragging them in React and storing them in the state

Hello! I've been using dragging in Full Calendar to save events in a state, but I'm running into an issue where it duplicates the event on the frontend. You can see an example of this problem here: https://codesandbox.io/s/fullcalendar-dragging-6 ...

What are your thoughts on CSS alignment?

Having difficulty aligning unordered lists the way I want. Below is an image of my desired layout, looking for guidance on achieving the version on the right side. I will be using between 1 and 6 unordered lists on different pages, so a universal solution ...

What is the best way to customize the appearance of the MUI TreeItem component within my unique theme

I am looking to apply custom colors to the MUI TreeItem component. While I came across this discussion, I prefer to achieve this using Theme style overrides within my own Theme. However, since TreeItem is not in the standard components list (but in '@ ...

Extract data from a JSON file and refine an array

Currently, I am working with reactjs and have an array stored in a json file. My current task involves filtering this array using the selectYear function. However, when attempting to filter the data using date.filter, I encounter the following error: An ...

Material Design Elements: Choosing Between Paper and Card Titles

When creating a React application, I aim to have the title of a Card or Paper positioned on the top border with some indentation from the left side. Here is an example: I have extensively searched for a universal method to achieve this layout but have not ...

The lengthy email exceeds its limits

Take a look at this code snippet: <div className='mt-[3vh] flex h-1/3 min-h-fit w-[80%] min-w-[300px] flex-col content-center items-center justify-center rounded-2xl bg-white shadow-[0_0_8px_rgba(0,0,0,0.2)]'> {user?.image && ...