CSS unable to modify the color of the switch in HTML code

I've been struggling to change the color of the Switch to yellow when it's turned on. Despite my attempts, I haven't been successful in doing so. Is it even possible to achieve this color change?

 <Switch
                size="small"
                checked={this.state.switchChecked}
                onClick={this.handleSwitchState}
                color="yellow"
              />

If anyone could lend a hand with this issue, I would greatly appreciate it. My goal is to have the Switch display a yellow color when toggled on.

Answer №1

If you want to personalize the color scheme, you'll need to utilize FormControlLabel in place of Switch, and then specify the desired colors within color, "&$checked", and

"&$checked + $track"
.

import React from "react";
import Switch from "@material-ui/core/Switch";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import { withStyles } from "@material-ui/core/styles";
import { yellow } from "@material-ui/core/colors";

const PurpleSwitch = withStyles ({
  switchBase: {
    color: yellow[300],
    "&$checked": {
      color: yellow[500]
    },
    "&$checked + $track": {
      backgroundColor: yellow[500]
    }
  },
  checked: {},
  track: {}
})(Switch);

class App extends React.Component {
  state = {
    switchChecked: false
  };

  handleSwitchState = () => {
    this.setState((prevState) => {
      return { switchChecked: !prevState.switchChecked };
    });
  };

  render() {
    const { switchChecked } = this.state;
    return (
      <FormControlLabel
        control={
          <PurpleSwitch
            checked={switchChecked}
            onChange={this.handleSwitchState}
            name="switchChecked"
          />
        }
        label="Yellow color"
      />
    );
  }
}

export default App;

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 process for setting up a MasterPage in React-Router-Redux that is connected to Redux?

I am looking to design a master page that will feature a navigation bar and login-profile section. The goal is to connect the login-profile section with redux in order to fetch data from a reducer. How can I achieve this within the App component? The App i ...

Struggling to navigate the use of Firebase v3 for hosting my React demo

I need assistance with hosting React apps on Firebase. I recently followed the instructions provided in the new v3 documentation on Firebase.com, but I am unsure about which files/assets should be placed in my public directory. The documentation seemed a b ...

Eliminate the dark backdrop from html5 videos that only shows up for a brief moment

Is there a way to remove the brief black background that appears when loading an HTML5 video? I have tried using CSS without success. The HTML: <div id="start-screen"> <video id="video-element"> <source src="video-mp4.mp4" type="vide ...

Sending information across React context

I've encountered a challenge when trying to transfer data from one context to another in React. The job data I receive from a SignalR connection needs to be passed to a specific job context, but I'm unsure of the best approach for achieving this. ...

What is the best way to maintain the current position in a component while interacting with another component?

I have a component that displays a collection of cards with images. There is a button that toggles between showing another component and returning to the original list of cards. The issue I am encountering is that every time I return to the list of cards, ...

Utilizing a created OpenAPI client within a React application

Using the command openapi-generator-cli generate -i https://linktomybackendswagger/swagger.json -g typescript-axios -o src/components/api --additional-properties=supportsES6=true, I have successfully generated my API client. However, despite having all th ...

The entered value in the <input> field is not valid

I am encountering an issue where the input value is auto-filled, but when I click the submit button, the input field value is not recognized unless I modify something in it, such as deleting and adding the last word to the first name. Is there a way to m ...

Exploring Font Choices: Customizing Your Text Style

I've been attempting to incorporate my own font into my website, but despite researching several Stack Overflow articles, I'm facing various browser-specific and path-related issues. Sadly, I haven't been able to successfully display my font ...

Troubleshooting React.createElement warning in Jest, Enzyme, and Styled Components integration

After creating styled components in a separate file with the same name and .css.jsx, such as Abc.jsx having Abc.css.jsx and importing it to utilize in Abc.jsx, an error is encountered when attempting to test Abc.jsx using Enzyme mount. Warning: React.creat ...

How do I solve the issue of not being able to use the 'in' operator to search for '1' in undefined within a react application?

I am eager to learn redux and redux toolkit but I seem to be encountering an issue. I am unsure of how to resolve it. My goal is to only store specific items in the users store. In this example, I want to store the following two items: id: '1' ...

The Material UI checkbox within the React hook form fails to update the isDirty state after the initial action

When using react hook form with MUI controlled checkbox within a formContext and fieldArray, the form's isDirty property does not get set on initial interaction. It only seems to update after a second action on the next checkbox. The desired behavior ...

Struggling with aligning images in the center of a square container

Currently revamping my photography website and working on a simple slider to showcase some of my photos. Struggling with aligning the images in divs with padding all around while keeping them centered. I want to replicate the look of my photos on Instagram ...

Creating React Context Providers with Value props using Typescript

I'd prefer to sidestep the challenge of nesting numerous providers around my app component, leading to a hierarchy of provider components that resembles a sideways mountain. I aim to utilize composition for combining those providers. Typically, my pro ...

"Maximizing battery life: Efficient video playback on iOS in low power

Summary: I am currently working on a website that features a video set as the background which autoplays. However, I have encountered an issue on iOS devices when "Low Power Mode" is activated - the video fails to play and instead displays a large "Play" i ...

Enhancing Functional Components with Idle Timeout using React Hooks

I am currently working on an application that requires implementing an idle timeout feature. This feature should first notify the user that they will be logged out in one minute, and then proceed to log them out after the time has expired. Previously, I s ...

Disable the movement and dragging functionality of the scroll feature in Google Maps using React

I have a map.jsx file in my React application that contains the code below: import React from 'react'; import GoogleMapReact from 'google-map-react'; import './map.css'; const Map = ({ location, zoomLevel }) => ( <d ...

No specified margin at the top of the website's header section

My task was to design the header section of a webpage to resemble this desired webpage look. I started by creating a "header" tag as a container and added a navbar within it. To display the items, I used an unordered list with CSS adjustments for a horizon ...

Design a unique <Link> component within my React shared UI library by utilizing a monorepo approach

As a newcomer to application architecture, I am eager to experiment with building an app using a Monorepo structure. I have a query regarding a Next.js frontend app that utilizes my React-based UI package shared across multiple apps within the same Monore ...

Using async await in a React component causes a syntax error

Struggling with setting up a basic react app using hapi.js on the server-side, I am diving into the world of webpack and babel as a newcomer. Here's a glimpse at my React component App.jsx: import React from 'react'; export default class A ...

Adjust the size of the child div to fit the remaining space within the parent div

I'm dealing with a situation where there are two child divs inside a parent div. The first child div takes up 32% of the width, while the second child div takes up 68% of the width. If I were to set the display of the first child div to "none", how ca ...