Adapting the colors of the MUI Switch component

I am currently utilizing the switch component from MUI and I am looking to change the styling between two different colors.

<Switch
  color={dataType === "expenses" ? "error" : "secondary"}
  onChange={handleOnSwitch}
  checked={dataType === "expenses"}
/>

I am having trouble identifying the specific props that need to be passed in order to customize the color of the off-switch state. The documentation only mentions props for the checked case, but I want to modify the switch color when it is unchecked to something other than the default gray.

Any assistance will be greatly appreciated.

Answer №1

To implement custom styles, you can use style props in the following manner:

<FormControl required>
  <FormLabel id="category-status" className={classes.inputLabel}>
    Status
  </FormLabel>
  <FormControlLabel
    control={(
      <Switch
        checked={formData?.Status}
        onChange={handleChange}
        name="Status"
        inputRef={statusRef}
        onKeyDown={(e) => handleFormEnterKey(e, IconURL)}
        style={{ color: formData?.Status === true ? '#33cf4d' : 'gray' }}
      />
    )}
   />
</FormControl>

Answer №2

Provided below is a sample code that can assist you in achieving the desired appearance by adjusting the styled codes.

import Switch from '@mui/material/Switch';
import { styled } from '@mui/material/styles';
import FormControlLabel from '@mui/material/FormControlLabel/FormControlLabel';

export default function BasicSwitches() {
  const MaterialUISwitch = styled(Switch)(() => ({
    width: 62,
    height: 34,
    padding: 7,
    '& .MuiSwitch-switchBase': {
      margin: 1,
      padding: 0,
      transform: 'translateX(6px)',
      '&.Mui-checked': {
        color: '#fff',
        transform: 'translateX(22px)',
        '& + .MuiSwitch-track': {
          opacity: 1,
          backgroundColor: 'blue',
        },
      },
    },
    '& .MuiSwitch-thumb': {
      backgroundColor: 'red',
      width: 32,
      height: 32,
      '&::before': {
        content: "''",
        position: 'absolute',
        width: '100%',
        height: '100%',
        left: 0,
        top: 0,
        backgroundRepeat: 'no-repeat',
        backgroundPosition: 'center',
      },
    },
    '& .MuiSwitch-track': {
      opacity: 1,
      backgroundColor: 'red',
      borderRadius: 20 / 2,
    },
  }));
  return (
    <div>
      <FormControlLabel
        control={<MaterialUISwitch sx={{ m: 1 }} defaultChecked />}
        label="MUI switch"
      />
    </div>
  );
}

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

Angular styling for input elements that are in the pristine state

Hey there, I'm working with a CSS class that applies a red border to an input field when it is required and invalid, and changes to green when it becomes valid. CSS .ng-valid[required], .ng-valid.required { border-left: 5px solid #42A948; /* green ...

Guide on adding up the value of a property within an array of objects using AngularJS

I am receiving an array of results from a Node.js API in my Angular app, and here is how it looks: <div *ngFor="let result of results"> <div *ngIf="result.harmattan.length > 0"> ... </div> <br> .. ...

The script fails to execute upon the loading of the view

I am facing an issue with a simple JavaScript code that aims to target an element within an angular view: var buttons = document.querySelectorAll('.msg-type i'); console.log(buttons.length); When I run this code, it incorrectly prints out 0 on ...

Implementing Cross-Origin Resource Sharing (CORS) in Express.js to facilitate communication between various ports

Struggling to make API calls using React and Axios from my front end (localhost:3000) to my back end (localhost:4567) is proving challenging. The consistent error message I encounter is: The CORS policy is blocking access to XMLHttpRequest at 'localh ...

Animate.css plugin allows for owl-carousel to smoothly transition sliding from the left side to the right side

I have a question regarding the usage of two plugins on my website. The first plugin is Owl Carousel 2, and the second one is Animate.css. While using `animateIn: 'slideInLeft'` with Owl Carousel 2 is working fine, I am facing an issue with `ani ...

Does a React functional component continuously re-render if it contains a child component?

For the past few days, I've been facing a performance issue in a React app (specifically React Native). The core of the problem is this: Whenever a function component Parent has another function component as its Child, the Parent will consistently re ...

Insert text into the cursor location within Summernote using JQuery

Currently, I am working on a flutter application where I have implemented the summernote editor using JQuery. ClipboardData data = await Clipboard.getData(Clipboard.kTextPlain); String txtIsi = data.text .replaceAll("'", '\&bsol ...

Bring in Icon from 'react-native-vector-icons/Ionicons' module

Is it possible to import both font-awesome and Ionicons icons from react-native-vector-icons on the same screen? I want to use different icons from each library on a single screen. For example: import ActionButton from 'react-native-action-button&apo ...

Retrieving the URL of an image from a webpage's photo gallery utilizing the Facebook Graph API with the help of Javascript

After trying out multiple tutorials, it appears that the latest version of the Graph API has caused some issues with my code. Here is the snippet I am working with: function fetchAlbumImages(){ FB.api( '/760126260690750/photos&ap ...

displaying an image that has been uploaded inside a div element

Is it possible to display the uploaded image within a red box? Here is the code snippet: http://codepen.io/anon/pen/ZWXmpd <div class="upload-image"> <div class="upload-image-preview"></div> <input type="file" name="file" val ...

Customize the CSS style of a component in VueJS

After creating styles for my website, I encountered a challenge. Users input specific content using a WYSIWYG editor, and I want this content to have a distinct style without affecting the rest of the site. Despite trying various methods like , I couldn& ...

When attempting to add a respond_to in ActionController, an ActionController::UnknownFormat error

After removing respond_to and render to view, everything seems to be working smoothly, but when I include the js render, I encounter an error. controller code : if params[:stock].present? @data = params[:stock] @stock = Stock.new_form_lookup(params[ ...

The unexpected outcome of ambient light in Three.js

Within the code snippet below, I am displaying some cubes and illuminating them with a PointLight and AmbientLight. Strangely, when the AmbientLight is set to 0xffffff, it changes the side colors to white regardless of their assigned colors. The point ligh ...

Creating a replica of a Parse Server object

I've been struggling to clone Parse objects without affecting the original ones. Despite trying various methods like Parse.Object.clone() and converting to JSON, I haven't found a working solution. I came across some recommendations online but no ...

What is the best way to share models across different node.js projects?

In my setup, I have two node.js projects - project A and project B. Project A serves as the main project, while project B is more of an "ad-hoc" project with a specific purpose. The challenge lies in the fact that project B requires access to project A&apo ...

Enhance your date with a specific month using MomentJS

I attempted to retrieve only the Saturdays of upcoming months with: var momentDt = moment('2017-03-18').add(1); //or 2 or 3 However, adding 1 results in April 18, 2017, which is a Tuesday. Is there an easier way in moment to achieve this wit ...

AngularJS -> Choice for specifying user's decimal format and limit restrictions

Is there a way to use AngularJS to dynamically limit user input to numbers between 0 and 1 with hundredths? For instance, if a user types 0, it should be converted to 0.00; if they type 1, it should become 1.00. I already have a JavaScript function for lim ...

Experience the power of ReactJS as you utilize the componentDidMount lifecycle method to fetch data

Currently, I am in the process of learning how to utilize ReactJS, Spotify API, and Promises. My goal is to retrieve top albums from musicians on Spotify and play a 30-second snippet of their tracks. I have decided to work with a Spotify package known as ...

Converting a ReadStream buffer into a permanent file

I've encountered a code block that I'm struggling to work with: fetchFile(file_id) { return new Promise((resolve, reject) => { var mongoose = require('mongoose'); var Grid = require('gridfs-stream'); ...

Unable to execute action in Jest

Our React app includes a cart component: import { useDispatch, useSelector } from "react-redux"; import ItemList from "./ItemList"; import { clearCart } from "../slice/cartSlice"; const Cart = () => { const dispatch = useDispatch(); const cartItems ...