Adjust the dimensions of the MaterialUI Switch component manually

Struggling to resize a Material-UI Switch as the default size isn't suitable. Managed to increase the size, but now the behavior isn't ideal.
It looks fine in its default state:
https://i.sstatic.net/qLpDZ.png.

However, when changing its state, it loses style:
https://i.sstatic.net/QL0of.png.

Unable to figure out how to alter the styles so the Thumb goes all the way to the right of the Track.

 <Switch
   onChange={setPrivateSwap}
   classes={{
     root: classes.root,
     switchBase: classes.switchBase,
     checked: classes.checked,
     track: classes.track,
     thumb: classes.thumb,
   }}
 />

const useStyles = makeStyles({
  root: {
    width: '90px',
    height: '50px',
    padding: 0,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
  track: {
    width: '40px',
    height: '20px',
    borderRadius: '10px',
  },
  switchBase: {
    '&$checked': {
      color: '#007D81',
    },
    '&$checked + $track': {
      backgroundColor: 'rgba(0,125,129,0.3)',
    },
  },
  checked: {},
  thumb: {
    width: '32px',
    height: '32px',
  },
});

Answer №1

Implementing the translateX(value) property on the switch has been successfully done in this snippet. Take a look at the code:

import React from "react";
import { Switch } from "@material-ui/core";
import { makeStyles } from "@material-ui/styles";

    const useStyles = makeStyles({
      root: {
        width: "90px",
        height: "50px",
        padding: 0,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      },
      track: {
        width: "40px",
        height: "20px",
        borderRadius: "10px",
      },
      switchBase: {
        "&$checked": {
          color: "#007D81",
          transform: "translateX(40px)",
        },
        "& + $track": {
          backgroundColor: "rgba(0,125,129,0.3)",
        },
      },
      checked: {},
      thumb: {
        width: "32px",
        height: "32px",
        transform: "translateX(0px)",
      },
    });
    
    export default function () {
      const classes = useStyles();
    
      const setPrivateSwap = function () {
        console.log("I a ali");
      };
      return (
        <Switch
          onChange={setPrivateSwap}
          classes={{
            root: classes.root,
            switchBase: classes.switchBase,
            checked: classes.checked,
            track: classes.track,
            thumb: classes.thumb,
          }}
        />
      );
    }

For additional customizations, feel free to experiment with further modifications using translateX within the thumb and switchBase classes.

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

Conceal a div element after redirecting to a different HTML page

I have a dilemma with my two HTML pages - index.html and register.html. I am trying to navigate from index.html to register.html, but I want to skip the select region step and go straight to the login page. Here's the code snippet I've been attem ...

Guide on navigating to a different page following a successful Google Sign In within React18

I'm facing an issue with redirection after signing in with Google on my React 18 project. Despite successfully logging in, the page does not redirect as expected. Below is a snippet of my Login.jsx file where the Google login functionality is implemen ...

Issue with jquery .click function not triggering after CSS adjustment

In the process of creating a fun game where two players take turns drawing on a grid by clicking <td> elements. Currently, I have implemented the functionality to toggle the background color of a <td> element from black to white and vice versa ...

Creating a function that allows for the dynamic addition of rows in Angular with

I am currently working on implementing search and filter functionality, which requires adding rows dynamically. With hundreds of fields to filter, my boss has decided to organize them in dropdown menus (such as Manager, City, and Name in this example). The ...

Discovering all mongoDB documents utilizing geolocation can be achieved by implementing specific queries that target

Utilizing the react geosuggest package, I am saving event locations in MongoDB. The data retrieved from Google Places gets stored in this format each time: "_id": "vvagbSbEginyrQGK8", "name": "test3", "googleLocation": { "label": "Testaccio, Roma, Ita ...

Contrast between the visibility settings of display none and display block

Can you explain the contrast between a control's style being set to display: none versus display: block? ...

Adding items to an array within another array in React

I have a collection of objects structured like this: { pksites: number; rooms: Room[]; } I am attempting to append the rooms to each object in the collection. Here is my implementation: collectionOfObjects.forEach((obj) => { obj.rooms ...

Step-by-step guide on incorporating CSS box-shadow with the .style JavaScript property

I have a JavaScript code snippet that looks like this: document.getElementById("imgA").style.box-shadow = "0 0 5px #999999"; The hyphen in box-shadow is causing an invalid assignment exception to be thrown by the JavaScript engine (specifically in Firefo ...

Challenges faced when dealing with MongoDB and the latest version of webpack

Struggling to navigate MongoDB and React.js, encountering issues with MongoDB dependencies. Here are the dependencies listed in package.json: "dependencies": { "dotenv": "^16.3.1", "mongodb": "^4.1.0", &qu ...

Utilize MySQL to populate highcharts with data

Learning the ropes of web programming, I have a personal project to monitor expenses. Simply put, my database stores data on total expenditures for this month and last month. I am able to display it manually (via echo), but I'm struggling to pass the ...

Comparing the process of retrieving data from a local host server in Create React App during the development phase to fetching from

I am currently working on my personal portfolio page and integrating a contact form using nodemailer. The nodemailer setup on the server side is all good but I need guidance on how to direct the client post request in terms of development and deployment. ...

Adjust the HTML content prior to displaying it to prevent any flickering

Is there a way to run code before the page is rendered, such as updating dates or converting text to HTML, without causing flickering when reloading multiple times? How can I ensure the code runs as it's drawn instead of waiting until the end to redra ...

Trouble displaying image due to issues with javascript, html, Angular, and the IMDb API integration

I have been working on displaying images from the IMDb API in my project. Everything works perfectly fine when I test it locally, but once I deploy the project to a server, the images do not load initially. Strangely, if I open the same image in a new tab ...

Tips for inserting values into a string array using jQuery or Angular 7

I have a series of checkboxes with values obtained from a loop. Instead of pushing these values into an array, I need to join them together as "parent1", "parent2", "parent3" and display the result in the console. Below is the code snippet for reference: ...

Link-defying button

I'm developing a website with a homepage that serves as an entry point to the rest of the site (it welcomes the user and allows them to click anywhere to access the main website). The following code accomplishes this: <template> <div onc ...

The loading indicator is not appearing inside the designated box

I have successfully implemented a loader using jQuery and CSS to display a gray background during an AJAX call. However, I am encountering an issue where the loader and background are being displayed across the entire page instead of just within a specific ...

Is it possible to rotate an image with a random angle when hovering in Angular?

I'm currently working on a photo gallery project and my goal is to have the images rotate when hovered over. However, I am experiencing difficulties in passing values from TypeScript into the CSS. HTML <div class="back"> <div cl ...

Leveraging the power of useContext in a React hook or incorporating a hook within useContext

When it comes to sharing state across components, I decided to implement a custom Context in my project. Within this context, I’m utilizing a custom hook called useChat() to handle the state variables. However, I have been pondering whether this is the b ...

Establishing the standard text color for MUI Typography

Having explored various examples, I now have a solid grasp on styling MUI's <Typography>. I've also mastered defining and implementing the global MUI theme. However, I'm curious if it's feasible for a MUI <Typography> to au ...

Creating visualizations by overlaying shapes onto images using specified coordinates in jQuery

I have a web application in development that integrates with the skybiometry API. Their demo showcases a fantastic user feedback system displayed after facial recognition, similar to the one shown below. I am currently working on implementing a similar fe ...