7.0.0 • Published 2 years ago

react-switch v7.0.0

Weekly downloads
142,389
License
MIT
Repository
github
Last release
2 years ago

A draggable toggle-switch component for React.

npm npm GitHub stars npm bundle size (minified + gzip)

  • Draggable with the mouse or with a touch screen.
  • Accessible to visually impaired users and those who can't use a mouse.
  • Customizable - Easy to customize size, color and more.
  • Small package size - Just 2 kb minified and gzipped.
  • It Just Works - Sensible default styling. Uses inline styles, so no need to import a separate css file.

Demo

Take a look at the demo

Installation

npm install react-switch

Usage

import React, { Component } from "react";
import Switch from "react-switch";

class SwitchExample extends Component {
  constructor() {
    super();
    this.state = { checked: false };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(checked) {
    this.setState({ checked });
  }

  render() {
    return (
      <label htmlFor="normal-switch">
        <span>Switch with default style</span>
        <Switch
          onChange={this.handleChange}
          checked={this.state.checked}
          id="normal-switch"
        />
      </label>
    );
  }
}

What's the deal with the label tag?

The Switch component in the above example is nested inside a label tag. The label tag has an htmlFor-value that is identical to the id-value that is passed to the Switch ("normal-switch"). These features are there to make the toggle-switch accessible to people with reduced sight who use screen readers. It will make screen readers read out the label text when the toggle-switch is selected. If you instead just put some text next to the switch, the screen reader will just read out "checkbox - not checked" or something like that and the user will have no idea what it is for. (The switch is actually a checkbox under the hood.)

It's not strictly necessary to both nest the switch inside the label AND use the htmlFor prop to link the label and the switch. It should be enough to do just one. However, using both will "cover 100% of assistive devices" and free you from annoying eslint errors.

Alternatively, you can use the aria-labelledby or aria-label props to give the switch a label. You can see examples of this at the bottom of the demo page.

API

PropTypeDefaultDescription
checkedboolRequiredIf true, the switch is set to checked. If false, it is not checked.
onChange (checked, event, id)funcRequiredInvoked when the user clicks or drags the switch. It is passed three arguments: checked, which is a boolean that describes the presumed future state of the checked prop (1), the event object (2) and the id prop (3).
disabledboolfalseWhen disabled, the switch will no longer be interactive and its colors will be greyed out.
offColorstring'#888'The switch will take on this color when it is not checked. Only accepts hex-colors.
onColorstring'#080'The switch will take on this color when it is checked. Only accepts hex-colors.
offHandleColorstring'#fff'The handle of the switch will take on this color when it is not checked. Only accepts hex-colors.
onHandleColorstring'#fff'The handle of the switch will take on this color when it is checked. Only accepts hex-colors.
handleDiameternumberundefinedThe diameter of the handle, measured in pixels. By default it will be 2 pixels smaller than the height of the switch.
uncheckedIconelement or boolDefault valueAn icon that will be shown on the switch when it is not checked. Pass in false if you don't want any icon.
checkedIconelement or boolDefault valueAn icon that will be shown on the switch when it is checked. Pass in false if you don't want any icon.
boxShadowstringundefinedThe default box-shadow of the handle. You can read up on the box-shadow syntax on MDN.
activeBoxShadowstring'0 0 2px 3px #3bf'The box-shadow of the handle when it is active or focused. Do not set this to null, since it is important for accessibility.
heightnumber28The height of the background of the switch, measured in pixels.
widthnumber56The width of the background of the switch, measured in pixels.
classNamestringundefinedSet as the className of the outer shell of the switch. Useful for positioning the switch.
idstringundefinedSet as an attribute to the embedded checkbox. This is useful for the associated label, which can point to the id in its htmlFor attribute.
aria-labelledbystringundefinedSet as an attribute of the embedded checkbox. This should be the same as the id of a label. You should use this if you don't want your label to be a \ element
aria-labelstringundefinedSet as an attribute of the embedded checkbox. Its value will only be seen by screen readers.

The following props have to be either 3-digit or 6-digit hex-colors: offColor, onColor, offHandleColor, and onHandleColor. This is because this library calculates intermediate color values based on the hex-color strings.

Examples of valid colors: '#abc', '#123456'

Examples of invalid colors: 'red', 'rgb(0,0,0)'

Development

You're welcome to contribute to react-switch.

To set up the project:

  1. Fork and clone the repository
  2. $ npm install
  3. $ npm run dev

The demo page will then be served on http://localhost:8000/ in watch mode, meaning you don't have refresh the page to see your changes.

Contributors

License

MIT

@bradleymarques/react-json-schema-form-builderreact-jsonschema-form-editor@lintondev/ui-kitmongodb-backup-guiminsilo-react-clientkhodroinja-ui-coreh5-spa-projecthybrid-librarygroupshybrid-librarygroups-testmircoai-gui@bradleymarques/react-json-schema-form-builder-forkhitutor-teach-platformlib-liberty-v-01lib-liberty-v-02lib-liberty-v-03lib-liberty-versionlibrary-liberty-version-0.0.1library-liberty-version-1.1.2@schoonlabs/blocks@adaliszk/redoc-extended@antiyro/componentsedisen-uicomments-library-v2rharuow-admin@everything-registry/sub-chunk-2616pw-testmapsampleblockzie-guitchin-react-componentstcomb-checkbox-switchsylksoft-admin-with-reduxsynapse-react-clientwpvibes-componentsxandarm-react-componentssampledataseedbox-downloaderscratchhw-guiscratch-arduino-guishort-interval-control-react-deckgl-componentrf-controlsrn-design-systemrol-formrm-hosted-widgetsuny-guistarr-commonstarr-vitesublime-uisparql-organizerstate-reducer-viewerscube-atomsscube-atoms-darkoutscube-atoms-newreact-native-web-uithiscar-next-appvm_digital_formexchange-react-uisusanoo-cmsmfe-user-templatemode-switchermock-server-fedlm-uikitlogistics-cardinal-uilearningtribes-studio-frontendlatest_form_builderhybrid-librarygroups-componentsinsomnia-componentsinvolv-ui-coreinspiratorlost-and-found-webappmetronic-reactledn-appkubeflow-kale-launcherkulbot-guigsaasgramene-searchgovin-guigrsbet-frontendkimmaisuikinetic-uikaygisiz-uijson-formikjelly-smart-crudhoi-poi-uinaveen_puchakayalamy-account-esmmc-componentesmat-periodic-tablepartikeloopy-design-systemopenblock-guioutro-component-catalogpolar-uikitpivot-table-enhancedpolitico-stylepipesort-admin-templateo-react-rol-formniuco-design-systemplatform-frontendnibi.ai.nlq
6.1.0

2 years ago

7.0.0

2 years ago

6.0.0

4 years ago

6.0.0-beta.0

4 years ago

5.0.1

5 years ago

5.0.0

6 years ago

5.0.0-beta.0

6 years ago

4.1.0

6 years ago

4.0.1

6 years ago

4.0.0

6 years ago

4.0.0-beta.0

6 years ago

4.0.0-alpha.0

6 years ago

3.0.4

6 years ago

3.0.3

6 years ago

3.0.2

6 years ago

3.0.1

6 years ago

3.0.0

6 years ago

3.0.0-beta.0

6 years ago

2.3.2

7 years ago

2.3.1

7 years ago

2.3.0

7 years ago

2.2.0

7 years ago

2.1.0

7 years ago

2.0.1

7 years ago

2.0.0

7 years ago

2.0.0-rc.2.1

7 years ago

2.0.0-rc.2

7 years ago

2.0.0-rc.1

7 years ago

1.2.0

7 years ago

1.1.0

7 years ago

1.0.0

7 years ago

0.1.0

10 years ago