最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to change size of Toggle Switch in Material UI - Stack Overflow

programmeradmin3浏览0评论

This is my first time using Material UI (I'm also a noob with react in general) and I cant seem to change the size of the toggle switch I'm using.

This is what I have so far -minus all the non related stuff:

import React, { Component } from "react";
import Switch from "@material-ui/core/Switch";


const styles = {
  root: {
    height: "500",
  },
};

class ToggleActive extends Component {
  state = {
    checked: true,
  };

  handleChange = name => event => {
    this.setState({ [name]: event.target.checked });
  };

  render() {
    return (
      <label htmlFor="normal-switch">
        <Switch
          classes={styles.root}
          checked={this.state.checked}
          onChange={this.handleChange("checked")}
        />
      </label>
    );
  }
}

export default ToggleActive;

I just want to make it a bit larger, and change the color. Any help would be appreciated!

This is my first time using Material UI (I'm also a noob with react in general) and I cant seem to change the size of the toggle switch I'm using.

This is what I have so far -minus all the non related stuff:

import React, { Component } from "react";
import Switch from "@material-ui/core/Switch";


const styles = {
  root: {
    height: "500",
  },
};

class ToggleActive extends Component {
  state = {
    checked: true,
  };

  handleChange = name => event => {
    this.setState({ [name]: event.target.checked });
  };

  render() {
    return (
      <label htmlFor="normal-switch">
        <Switch
          classes={styles.root}
          checked={this.state.checked}
          onChange={this.handleChange("checked")}
        />
      </label>
    );
  }
}

export default ToggleActive;

I just want to make it a bit larger, and change the color. Any help would be appreciated!

Share Improve this question edited Jul 8, 2018 at 11:02 Tholle 113k22 gold badges208 silver badges196 bronze badges asked Jul 8, 2018 at 11:00 Ariel SolanoAriel Solano 1813 gold badges3 silver badges7 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

The change in the Switch ponent requires a little bit of detailed styling. I added some ments in parts that are not very obvious:

import {createStyles, makeStyles, Switch, Theme} from '@material-ui/core';

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      width: 54,
      height: 40,
      padding: 0,
      margin: theme.spacing(1),
    },
    switchBase: {
      padding: 1,
      '&$checked': {
        // This is the part that animates the thumb when the switch is toggled (to the right)
        transform: 'translateX(16px)',
        // This is the thumb color
        color: theme.palette.mon.white,
        '& + $track': {
          // This is the track's background color (in this example, the iOS green)
          backgroundColor: '#52d869',
          opacity: 1,
          border: 'none',
        },
      },
    },
    thumb: {
      width: 36,
      height: 36,
    },
    track: {
      borderRadius: 19,
      border: `1px solid ${theme.palette.grey[300]}`,
      // This is the background color when the switch is off
      backgroundColor: theme.palette.grey[200],
      height: 30,
      opacity: 1,
      marginTop: 4,
      transition: theme.transitions.create(['background-color', 'border']),
    },
    checked: {},
    focusVisible: {},
  })
);

You can implement this as a functional ponent:

import React, { useState } from 'react';
// import {createStyles, makeStyles, ...

// const useStyles = makeStyles((theme: Theme) => ...

export const ToggleItem: React.FC = () => {
  const styles = useStyles();
  const [toggle, setToggle] = useState<boolean>(false);

  return (
    <Switch
      classes={{
        root: styles.root,
        switchBase: styles.switchBase,
        thumb: styles.thumb,
        track: styles.track,
        checked: styles.checked,
      }}
      checked={toggle}
      onChange={() => setToggle(!toggle)}
      name={title}
      inputProps={{'aria-label': 'my toggle'}}
    />
  );
};

This is now even easier to acplish because MUI has an official example in the documentation:

https://mui./material-ui/react-switch/#customization

Using that as an example, the minimum number of changes to acplish making the switch bigger is actually just this:

export const MuiSwitchLarge = styled(Switch)(({ theme }) => ({
  width: 68,
  height: 34,
  padding: 7,
  "& .MuiSwitch-switchBase": {
    margin: 1,
    padding: 0,
    transform: "translateX(6px)",
    "&.Mui-checked": {
      transform: "translateX(30px)",
    },
  },
  "& .MuiSwitch-thumb": {
    width: 32,
    height: 32,
  },
  "& .MuiSwitch-track": {
    borderRadius: 20 / 2,
  },
}));

Here is the link to a forked sandbox with just a bigger switch: https://codesandbox.io/s/customizedswitches-material-demo-forked-4m2t71

I found transforming the whole Switch to be much simpler than diving into the in's and out's of mui styling.

<Switch sx={{ transform: "scale(1.5)" }} />

Now we have a switch thats 50% bigger than usual

Consider this: I am not a front-end developer and did not develop in Material-UI framework for years now. so just look for a different answer or send me an edit version which works.

For changing the size of the switch ponent you should use size props that can be in two size 'small' || 'medium'.For example:

<Switch
   size="small"
   checked={this.state.checked}
   onChange={this.handleChange("checked")}
   color='primary'
/>

If it doesn't work for you then You need to change CSS style at root class:

const styles = {
     root: {
        height: 500,
        width: 200},
};

Due to material-UI ponent API for changing the color of a switch you need to add a color props into you Switch JSX tag and choose from these enum:

  enum: 'primary' |'secondary' | 'default'

your Switch should be like this:

<Switch
   classes={styles.root}
   checked={this.state.checked}
   onChange={this.handleChange("checked")}
   color='primary'
/>

Material-UI for switch size prop

发布评论

评论列表(0)

  1. 暂无评论