GithubHelp home page GithubHelp logo

markusenglund / react-switch Goto Github PK

View Code? Open in Web Editor NEW
1.3K 9.0 101.0 2.01 MB

A draggable toggle-switch component for React. Check out the demo at:

Home Page: https://react-switch.netlify.com/

License: MIT License

JavaScript 100.00%

react-switch's Introduction

A draggable toggle-switch component for React.

npm npm GitHub stars gzip size

  • Draggable with the mouse or with a touch screen.
  • Customizable - Easy to customize size, color and more.
  • Accessible to visually impaired users and those who can't use a mouse.
  • Reasonable package size - <2.5 kB 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>
        <span>Switch with default style</span>
        <Switch onChange={this.handleChange} checked={this.state.checked} />
      </label>
    );
  }
}

What's the deal with the label tag?

The Switch component in the above example is nested inside a label tag. This makes sure that the label text is read out to people with reduced sight who use screen readers and enables users to click on the text to toggle the switch. If you would only put some text next to the switch but not inside a label element, the screen reader will just read out "switch off" and the user will have no idea what it is for.

If you don't want to nest the switch inside a label, you can use the htmlFor attribute on the label-element and set it to the same value as the id of the switch. 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

Prop Type Default Description
checked bool Required If true, the switch is set to checked. If false, it is not checked.
onChange ([checked], [event], [id]) func Required Invoked 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).
disabled bool false When disabled, the switch will no longer be interactive and its colors will be greyed out.
offColor string '#888' The switch will take on this color when it is not checked. Only accepts hex-colors.
onColor string '#080' The switch will take on this color when it is checked. Only accepts hex-colors.
offHandleColor string '#fff' The handle of the switch will take on this color when it is not checked. Only accepts hex-colors.
onHandleColor string '#fff' The handle of the switch will take on this color when it is checked. Only accepts hex-colors.
handleDiameter number undefined The diameter of the handle, measured in pixels. By default it will be 2 pixels smaller than the height of the switch.
uncheckedIcon element or bool Default value An icon that will be shown on the switch when it is not checked. Pass in false if you don't want any icon.
checkedIcon element or bool Default value An icon that will be shown on the switch when it is checked. Pass in false if you don't want any icon.
uncheckedHandleIcon element undefined An icon that will be shown on the handle of the switch when it is not checked.
checkedHandleIcon element undefined An icon that will be shown on the handle of the switch when it is checked.
boxShadow string undefined The default box-shadow of the handle. You can read up on the box-shadow syntax on MDN.
activeBoxShadow string '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.
height number 28 The height of the background of the switch, measured in pixels.
width number 56 The width of the background of the switch, measured in pixels.
className string undefined Set as the className of the outer shell of the switch. Useful for positioning the switch.
borderRadius number undefined Border radius of the switch and the handle.
id string undefined Set as an attribute to the embedded checkbox. This is useful for the associated label, which can point to the id in its htmlFor attribute.

NOTE: All additional props will be passed to the nested input element.

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. Keep in mind that big changes have to be thoroughly tested on lots of different browsers and devices before they can be merged.

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


Markus Englund

Timothy McLane

License

MIT

react-switch's People

Contributors

hakonkrogh avatar iamgutz avatar jorrit avatar markusenglund avatar morinted avatar notrebel avatar originalexe avatar sag1v avatar smhg avatar timothymclane avatar valerybugakov avatar xiao-hu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-switch's Issues

custom border style

Is it possible to add border style to the component?
I want to add style for the component with react-swith-bg class and to the component with react-switch-handle class.

Thanks

Flickering switch.

Hey there.

I'm using this for my portfolio as a dark/light mode toggle. Functionally; it works great, however, there's a slight issue with how it interacts with my theme toggling plugin.

<ThemeToggler>
              {({ theme, toggleTheme }) => (
                <div className="toggle-container">
                  <Switch
                    checked={theme === "dark"}
                    onChange={checked => toggleTheme(checked ? "dark" : "light")}
                    checkedIcon={<span aria-label="moon" role="img" className="toggle-icon">๐ŸŒ‘</span>}
                    uncheckedIcon={<span aria-label="sun" role="img" className="toggle-icon">๐ŸŒž</span>}
                    offColor="#ff145a"
                    onColor="#a0a5ff"
                    height={28}
                    width={56}
                    handleDiameter={20}
                  />
                </div>
              )}
            </ThemeToggler>

I'm using it as part of a render prop which I believe is leading to the switch being a tad delayed to update as it's dependent on the theme value from said render prop. You can visit my portfolio to see this in effect. If dark mode is enabled, switching pages will cause the switch to flicker into the unchecked state for a frame or two before returning to the checked state.

I forked your code and tried to fix this with shouldldComponentUpdate() but didn't seem to work too nicely so I wanted to put this out there and see if you'd experienced this issue before and if this could be rectified in future.

Not disabled completely when disabling

import SwitchButton from 'react-switch'
<SwitchButton disabled=false height={20} width={48} className='react-switch' id='material-switch' />

Even though it is disabled, when I am dragging it, it is still working, but when I am clicking it, it is not working.

HTML order. Input is last.

Hi,

Can you check HTML input's order like that.

image

It will be better, as I could properly use CSS tidle (~) selector to control handle.

Something like that:

input:focus ~ .react-switch-handle {........}

Better color hex validation

I think there could be a better color validation, since 4-digit hex values are perfectly fine and offer unique colors. Ie. all the hexes below are valid:

#aadd
#abcd
#affa
#baba
#dada
#cace

I've been working on a color validation package that could help:

https://www.npmjs.com/package/validate-color

This is how it could be applied to hexColorPropType.js:

import { validateHTMLColorHex } from 'validate-color';

// Make sure color props are strings that start with "#" since other ways to write colors are not supported.
const hexColorPropType = (props, propName, componentName) => {
  const prop = props[propName];
  if (
    !validateHTMLColorHex(prop)
  ) {
    return new Error(
      `Invalid prop '${propName}' supplied to '${componentName}'. '${propName}' has to be a hex-color string. Valid examples: '#abc', '#dada', '#123456'`
    );
  }
  return null;
};

export default hexColorPropType;

Zero length drags should count as clicks

Sometimes clicking on the switch in the demos seems to have no effect.

I've not fully verified this because the minified code is hard to debug, but my theory (based on debugging other drag&drop UIs) is that I'm inadvertently moving the mouse during the click by a distance less than 1 pixel which still triggers a drag event, and so the intended click has no effect.

The solution would be to ignore initial drag events below a certain drag threshold drag distance.

It may be that this effect only occurs with apple mice with the sensitivity turned up high.

Label click doesn't trigger checkbox

Hello,

Firstly thanks for the module, it is really good and it take us very few time to set up our Graphic Identity with it ๐Ÿ‘

I'm posting this issue because i'm really struggling to allow checkbox check via label click, i'm using the exact same code as the demo but nothing happen.

Do you have any idea what can cause this issue ?

Best regards,

handle width and height

Hello,

It would be great to be able to change width and height of the handle, not only the diameter :

image

thanks !

a11y: aria-checked

The input has role="switch", but has no corresponding aria-checked.

This is flagged for a site doing a Lighthouse accessibility audit.

Screenshot 2019-12-16 at 14 50 17

onColor and offColor transparent

Hello.
I set 'transparent' color for onColor and offColor. It's working but shows errors in console:
Invalid prop 'onColor' supplied to 'ReactSwitch'. 'onColor' has to be either a 3-digit or 6-digit hex-color string. Valid examples: '#abc', '#123456'

Switches on/off with icon

Hi @markusenglund ,

Instead of the usual colored Switche on/off, it would be a nice feature to have a Switche with icons that are passed, even the colors must be passed, so if it is in the on state it has a different color and icon than what it is state is off.

introducingPhone1

codesandbox

Schermata da 2020-02-11 14-02-56

Schermata da 2020-02-11 14-04-08

redux-form

It's possible to use this component with redux-form?

Allow for text instead of icons

I put a div with some text in the field, like this:


<ReactSwitch className='FilterSwitch'
              onChange={this.onFilterClick}
              checked={this.state.showOptionPanel}
              uncheckedIcon={<div className='uncheckedIcon'>NO FILTERS</div>}
              checkedIcon={<div className='checkedIcon'>FILTERS</div>}
              height={isMobile ? 25 : 20}
              width={isMobile ? 100 : 90}
/>

It worked as long as I used labels like 'on' and 'off', but rendered strangely when I used larger words like 'Filtered' and 'Unfiltered'.

I fixed that with minor changes index.jsx, allowing for fixed with via the property. It just adds a ternary to the calculation of width within checkedIconStyle and uncheckedIconStyle:

const checkedIconStyle = {
            height,
            width: this.props.width ? (this.props.width - this.$handleDiameter) : Math.min(
                height * 1.5,
                width - (this.$handleDiameter + height) / 2 + 1
            ), ...

Works like a charm for me, although the user has to manually take over styles for the text, as it generally requires changes to font size and margins to look good. This worked for me:

.checkedIcon, .uncheckedIcon {
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  font-size: .7rem;
  font-weight: bold;
  font-variant: small-caps;
}

.checkedIcon {
  padding-left: 4px;
}

.uncheckedIcon {
  padding-left: 2px;
}

Plus a little change when using mobile/small screens with a media query:

.uncheckedIcon, .checkedIcon {
    font-size: .7rem;
    padding-left: .3rem;
    padding-right: .3rem;
  }

Add option to customize border-radius

Thank you for this package. Would it be possible to add a prop to customize the border radius, to allow for squarer switches, e.g. like this?:

image
image

Alternatively a more direct way to style the handle and background would be nice, i.e. what was proposed in #15 .

Colors control

Hi,

First of all, thanks for this great package. Really well implemented, though I would like more control on colouring.

These said, I want to propose a feature request. I'd like to be able to change colors when the button is disabled, but more important, to override the current color when I want to display an error, something like the example below.

screen shot 2018-11-03 at 07 32 39

This is how i use it:

               switchId = "#{w._id}-#{section[0]}"
               <Switch
                    checked         = {@state.checked?[switchId]}
                    onChange        = {(checked, e, id) => @onSwitchChange(checked, section[0], w._id, id)}
                    disabled        = {@state.disabled?[switchId]}
                    uncheckedIcon   = {false}
                    checkedIcon     = {false}
                    onColor         = "#D0E2FF"
                    offColor        = {Colors.appBg}
                    onHandleColor   = {Colors.primaryColor}
                    boxShadow       = "0px 1px 5px rgba(0, 0, 0, 0.6)"
                    activeBoxShadow = "0px 0px 5px 5px #D0E2FF"
                    handleDiameter  = {24}
                    height          = {16}
                    width           = {40}
                    id              = {switchId}
               />

Maybe you cand add a fourth state: hasError and ability to set the colors on error state

I would like to have something like

             <Switch
                ...
                disabled            = {true/false}
                disabledHandleColor = 'color'
                disabledBodyColor   = 'color' # not sure about 'body', but you've got the point
                hasError            = {true/false}
                errorHandleColor    = 'color'
                errorBodyColor      = 'color'
              />

Waiting for your feedback.

Thanks!

Can you add title please

Hi there,

When I added the html title to the switch, and it didn't work. Then I checked, the title attribute is missing. Can you add it, please?

Thank you,

Add onHoverColor and offHoverColor as props

Having separate props for hover colors would be beneficial, it's a small but meaningful interaction that makes the switch more lively and active from the user's perspective.

Rewrite for Hooks / React 16.8?

Hi, Your component has the best functionality I've found in react switches or toggles. Is it possible to use it as-is using hooks? Is there a plan to include hooks support in the future? Thanks!!!

Allow aria props

I saw that aria-label and aria-labelledby are accepted props to the component, but there are a number of others that are required based on a given element's state. It would be nice if:

  1. All aria-* props are explicitly whitelisted, OR
  2. The component used the ...restProps syntax to allow passing any unanticipated properties to the component without the need to whitelist them individually

The specific prop that I came here about is aria-checked, which is required for checkbox inputs (see https://dequeuniversity.com/rules/axe/3.1/aria-required-attr).

Time to update dependencies, maybe?

Since package.json lists react as react: ^16.7.0 (released on 2018.12.20), I guessed my way to the closest node LTS at the time: 8.14.1 (released on 2018.12.18).

Based on that, I installed the dependencies locally and got the following result:

Screenshot 2020-02-16 at 23 16 35

That's a lot of time since then so this update might not be the most trivial, but maybe it's worth a try?

I usually hesitate to open PRs with so obtrusive changes, since they tend to not get merged...

Calls to setState when component is unMounted

When clicking on the handle, if the component is unMounted, it will call setState in $onDragStop. I have tried adding a componentWillUnmount and remove listeners, but that did not do the trick...

When clicking on handler, click event propagates.

Hello,
I am using the switch inside a user component in a list.
Clicking on the user component displays the user details.

switch in user component

What should happen:
Clicking on the switch (handle included) should toggle an attribute on the user without showing the user details.

What happens instead:
Clicking on the switch handle triggers displaying the user details (a callback on the user component).

Even when I add e.stopPropagation in the onChange callback, it still propagates.

This maybe related to issue 21 but the solution provided there did not fix this propagation issue.

Switch using aria-labelledby not working

Hi,

I like the switch but I cannot figure out how to stop the switch from switching when the user clicks on the label

Note

I have left out all of the handlers and state functionality... that all works...

How Used

This is where the switch is used:

  render() {
     let  Content = ( 
      <div>
        {switch_isProcessing}
      </div> 
      );

    return (
      <div className="garminRegister">
        <div className="container">
          {Content}
        </div>
      </div>
    );
}

Current Definition

This is how I currently define the label, which, when I click on "Process Garmin data" the switch moves.

    let switch_isProcessing = (
      <div className="rowC">

        <label>
          <span className="rightSpace">Process Garmin data</span>
          <Switch 
            onChange={value => this.handleChange('isProcessing', value)} 
            checked={isProcessing} 
            id="isProcessing-switch"
            className="react-switch"

            onColor="#b9721b"
            onHandleColor="#50be55"
            handleDiameter={30}
            uncheckedIcon={<div>Off</div>}
            checkedIcon={
              <div
                style={{
                  display: "flex",
                  justifyContent: "center",
                  alignItems: "center",
                  height: "100%",
                  fontSize: 15,
                  color: "bisque",
                  paddingRight: 2
                }}
              >
                On
              </div>}
            boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
            activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)"
            height={25}
            width={50}
            />
        </label>

      </div>
    );   

Attempts

I am progressively moving the ID to a parent

Try 1

First attempt

    let switch_isProcessing = (
      <div className="rowC">

        <label>
          <span id="neat-label" className="rightSpace">Process Garmin data</span>
          <Switch 
            onChange={value => this.handleChange('isProcessing', value)} 
            checked={isProcessing} 
            id="isProcessing-switch"
            aria-labelledby="neat-label"
            className="react-switch"

            onColor="#b9721b"
            onHandleColor="#50be55"
            handleDiameter={30}
            uncheckedIcon={<div>Off</div>}
            checkedIcon={
              <div
                style={{
                  display: "flex",
                  justifyContent: "center",
                  alignItems: "center",
                  height: "100%",
                  fontSize: 15,
                  color: "bisque",
                  paddingRight: 2
                }}
              >
                On
              </div>}
            boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
            activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)"
            height={25}
            width={50}
            />
        </label>

      </div>
    );   

Try 2

    let switch_isProcessing = (
      <div className="rowC">

        <label id="neat-label">
          <span className="rightSpace">Process Garmin data</span>
          <Switch 
            onChange={value => this.handleChange('isProcessing', value)} 
            checked={isProcessing} 
            id="isProcessing-switch"
            aria-labelledby="neat-label"
            className="react-switch"

            onColor="#b9721b"
            onHandleColor="#50be55"
            handleDiameter={30}
            uncheckedIcon={<div>Off</div>}
            checkedIcon={
              <div
                style={{
                  display: "flex",
                  justifyContent: "center",
                  alignItems: "center",
                  height: "100%",
                  fontSize: 15,
                  color: "bisque",
                  paddingRight: 2
                }}
              >
                On
              </div>}
            boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
            activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)"
            height={25}
            width={50}
            />
        </label>

      </div>
    );   

Try 3

    let switch_isProcessing = (
      <div id="neat-label" className="rowC">

        <label>
          <span className="rightSpace">Process Garmin data</span>
          <Switch 
            onChange={value => this.handleChange('isProcessing', value)} 
            checked={isProcessing} 
            id="isProcessing-switch"
            aria-labelledby="neat-label"
            className="react-switch"

            onColor="#b9721b"
            onHandleColor="#50be55"
            handleDiameter={30}
            uncheckedIcon={<div>Off</div>}
            checkedIcon={
              <div
                style={{
                  display: "flex",
                  justifyContent: "center",
                  alignItems: "center",
                  height: "100%",
                  fontSize: 15,
                  color: "bisque",
                  paddingRight: 2
                }}
              >
                On
              </div>}
            boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
            activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)"
            height={25}
            width={50}
            />
        </label>

      </div>
    );  

Not a bug as such - In Responsive Design Mode in Firefox clicking causes 2 actions. - seems ok in Chromes reactive mode

I borrowed this demo from another issue as it shows the behavior I experienced in a local app.
https://codesandbox.io/s/vmwpv6x2ql

If I run the demo in Firefox then open the output in a new window, in that new window open developer tools and enable Responsive Design Mode. Then clicking (not dragging) on the react-switch-handle in and off state will fire onChange twice off then on, similarly clicking in an on state will fire onChange twice on then off.

Attached a video capture of it, the drag works fine but single click shows double action.

example-react-switch-double-action

Testing in Chrome and Firefox on Android it doesn't show this behavior, its only the Firefox Responsive design mode so this isn't a bug IMO just thought its worth knowing about and being concious of.

Strange switch behavior on click over the dragging pill

I installed and used the component, version 3.0.4. It works perfectly when I click on the V or X parts of the switch, but it acts weird when I click on the dragging pill: the switch of the status does not happen immediately (but this actually happens in the examples), but it remains in a sort of dangling status where the pill follows the mouse cursor even if I move it to other parts of the web application. In order to "unlock" it, I must click again on the switch.
This does not happen in the examples page.

This seems to be solved for me by downgrading to 2.3.2.

Label Issues

Usually, when a label is attached to a checkbox/radio and the user clicks on the label, it toggles the button. That functionality doesn't seem to work with this switch. It might be nice to add that in.

Value doesn't change if clicked on handle if Chrome not in focus

Repro:

  1. Open official demo in a Chrome (I have version 70, but i think i've seen this on previous versions)
  2. Open another application (i have Windows 10 though) and focus it
  3. Click on handle -> doesn't trigger the change, just the focus

If you click not on the handle itself, it's working fine

#8 Can be related

Last Edge and Firefox also working fine

TypeScript error while using react-switch.

Hi,

I am having the following error when I try to use this library.

The following code:

import * as React from "react";
import Component from "../../AbstractComponent";
import Switch from "react-switch";

export class SwitchComponent extends Component {

  public state = {
    checked: false
  };

  constructor(public props) {
    super(props);

    this.handleChange = this.handleChange.bind(this);
  }

  public handleChange(checked) {
    this.setState({
      checked: checked
    }, () => {
      if (this.props.onChange) {
        this.props.onChange.call(this, this.state);
      }
    });
  }

  public render() {
    return (
      <label htmlFor="normal-switch" className="switch-container">
        <Switch
          checked={this.state.checked}
          onChange={this.handleChange}
          onColor="#86d3ff"
          offColor="#B2BEC4"
          onHandleColor="#2693e6"
          handleDiameter={20}
          uncheckedIcon={false}
          checkedIcon={false}
          boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
          activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)"
          height={20}
          width={40}
          className="react-switch"
        />
      </label>
    );
  }
}

produces:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. Check the render method of Component.

It works when I use * import syntax, but TypeScript gives the following error in that case.

`JSX element type 'Switch' does not have any construct or call signatures.

Allow *Color to accept css variables, not only hex-colors

Allow offColor, onColor, offHandleColor and onHandleColor to accept css variables, not only hex-colors.

In our project we use css vars to handle themes and we use them to customize components. But react-switch component doesn't allow to do this.

I would like to use switch component like this:

<Switch
	checked={value}
	onChange={onChange}
	onColor="var(--switch-on-color)"
	offColor="var(--switch-off-color)"
/>

height not working

                 <Switch
                        defaultValue={false}
                        offColor="success"
                        offText="OFF"
                        onColor="success"
                        onText="ON"
                        height={10}
                      />

the default width and height are !important so those don't work

Pass id in onChange

Not quite sure about pull requests etc....

I need to pass the id of the component back with new value, so I know which switch changed.

Cheers

diff --git a/src/index.jsx b/src/index.jsx
index 9587351..b9c9fa6 100644
--- a/src/index.jsx
+++ b/src/index.jsx
@@ -38,12 +38,12 @@ class Switch extends Component {
 
   handleDragStop = (event) => {
     const { pos, isDragging } = this.state;
-    const { checked, onChange } = this.props;
+    const { checked, onChange, id } = this.props;
 
     // Simulate clicking the handle
     if (!isDragging) {
       this.setState({ startX: null, hasOutline: false });
-      onChange(!checked, event);
+      onChange(!checked, id, event);
       return;
     }
     if (checked) {
@@ -52,7 +52,7 @@ class Switch extends Component {
         return;
       }
       this.setState({ startX: null, isDragging: false, hasOutline: false });
-      onChange(false, event);
+      onChange(false, id, event);
       return;
     }
     if (pos < (this.checkedPos + this.uncheckedPos) / 2) {
@@ -60,7 +60,7 @@ class Switch extends Component {
       return;
     }
     this.setState({ startX: null, isDragging: false, hasOutline: false });
-    onChange(true, event);
+    onChange(true, id, event);
   }
 
   handleMouseDown = (event) => {
@@ -101,17 +101,17 @@ class Switch extends Component {
   }
 
   handleClick = (event) => {
-    const { checked, onChange } = this.props;
-    onChange(!checked, event);
+    const { checked, onChange, id } = this.props;
+    onChange(!checked, id, event);
   }
 
   handleKeyDown = (event) => {
-    const { checked, onChange } = this.props;
+    const { checked, onChange, id } = this.props;
     const { isDragging } = this.state;
     // Trigger change on spacebar and enter keys (in violation of wai-aria spec).
     if ((event.keyCode === 32 || event.keyCode === 13) && !isDragging) {
       event.preventDefault();
-      onChange(!checked, event);
+      onChange(!checked, id, event);
     }
   }
 

Feature: add `disabledOpacity` prop

Currently the opacity is injected as inline style and set to 0.5 when the component is disabled.

I want to lower the value to 0.4, but if I set it via css, I have to put the !important flag which reduce the customization ability of the user of my lib.

So is it ok to add such a property? or just allow us to set a style object wich could override the default one?

Changing handleDiameter prop doesn't have any affect on the handle size

When I try to change the handleDiameter prop, it doesn't have any affect on the handle size. While the width and height props does update the width and height of the outer container. It seems to be happening due to

this.$handleDiameter = handleDiameter || height - 2;

in the constructor. Is there a way to fix this?

Actually I'm using react-switch as a toggle button in one of the widgets I'm working on and I want to have different width and height of the toggle button based on the viewport. Though the width and height props of the switch component does but the width and height of container, the handle diameter doesn't update the handle size.

Accept `tabIndex` prop

As a developer, it would be beneficial to declare a tab index for the switch. Currently the behavior is that it gets set to "0" by the internals, or null if the switch is disabled.

Switch is only draggable, not toggled by click

I'm on React 16.12.0 and react-switch 5.0.1

When I render react-switch it is only draggable, but does not change/toggle when I click it. I found this issue however that seemed related to an iFrame which I'm not using.

I put a console.log(checked) in the handleChange function and it always outputs false regardless of what the state of the switch is.

Below is the component I'm loading the switch in. My only guess is it might have something to do with the async methods or with me setting the state in the View() function, but it's not clear to me what I'm doing wrong.

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

import HidingContainer from "../HidingContainer"
import NumericValue from "../NumericValue/index"


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

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

  async componentDidMount() {
    await this.View();
  }

  CustomSwitch = () => {
    return (
      <Switch
        onChange={this.handleChange}
        checked={this.state.checked}
        onColor="#86d3ff"
        onHandleColor="#2693e6"
        handleDiameter={30}
        uncheckedIcon={false}
        checkedIcon={false}
        boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
        activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)"
        height={20}
        width={48}
        className="react-switch"
        id="material-switch"
      />
    )
  }

  async getHotTubStatus() {
    const response = await axios({
      url: "http://localhost:3000/hot-tub-status",
      method: 'get'
    });

    return response.data
  }

  async View() {
    const hotTubStatus = await this.getHotTubStatus()

    this.setState({
      checked: hotTubStatus.on, // sets initial state
      View: (
        <NumericValue value={hotTubStatus.temperature} unit="ยฐF" />
        <this.CustomSwitch />
      )
    })
  }

  render() {
    return (
      <HidingContainer metricsRef={React.createRef()}>
        {this.state.View}
      </HidingContainer>
    )
  }
}

export default HotTub

Any insight/help appreciated

Setting css direction to rtl will break the switch design

hi there,

Thank you very much for this component, this is the only one I have found with all the necessary options.

Unfortunately, I have found one problem with this component; setting the css 'direction:rtl' of the switch container will break the switch design:

Capture

wondering if you have any suggestion for this problem.

Thanks,

Click doesn't toggle switch, only dragging works

I'm attaching a gif showing the behavior. When I click on the switch it doesn't do anything at all. It can only be toggled by dragging it and even then the animation makes a jump.
https://gfycat.com/VagueNeglectedBonobo

I'm using React 16.8.1 and react-switch 4.0.1 in a create-react-app project where I manually updated React. Here's how I'm using the switch:

<Switch
          onChange={checked => console.log(checked)}
          width={112}
          height={45}
          onColor={colorPalette.primary}
          offColor={colorPalette.gray}
          offHandleColor={colorPalette.dark}
          handleDiameter={30}
          uncheckedIcon={false}
          checkedIcon={false}
          checked={isRunning}
          onColor="#2e91e9"
          id="normal-switch"
  />

What could be causing the behavior?

Thanks!

This package works really well; thank you for sharing! โค๏ธ

Prevent Swipe On Dragging

Local state update cannot be blocked while dragging.

Case: If switch update depend on some conditions and conditions not suitable for update switch state, state update should not be allowed while dragging..

New props can be added to avoid updating the local state on dragging issue.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.