Code Monkey home page Code Monkey logo

react-native-switch's Introduction

react-native-switch

Customisable switch component for RN and React Native Web

Installation

$ npm install --save react-native-switch

or

yarn add react-native-switch

Usage

import { Switch } from 'react-native-switch';

export const App = () => (
  <Switch
    value={true}
    onValueChange={(val) => console.log(val)}
    disabled={false}
    activeText={'On'}
    inActiveText={'Off'}
    circleSize={30}
    barHeight={1}
    circleBorderWidth={3}
    backgroundActive={'green'}
    backgroundInactive={'gray'}
    circleActiveColor={'#30a566'}
    circleInActiveColor={'#000000'}
    renderInsideCircle={() => <CustomComponent />} // custom component to render inside the Switch circle (Text, Image, etc.)
    changeValueImmediately={true} // if rendering inside circle, change state immediately or wait for animation to complete
    innerCircleStyle={{ alignItems: "center", justifyContent: "center" }} // style for inner animated circle for what you (may) be rendering inside the circle
    outerCircleStyle={{}} // style for outer animated circle
    renderActiveText={false}
    renderInActiveText={false}
    switchLeftPx={2} // denominator for logic when sliding to TRUE position. Higher number = more space from RIGHT of the circle to END of the slider
    switchRightPx={2} // denominator for logic when sliding to FALSE position. Higher number = more space from LEFT of the circle to BEGINNING of the slider
    switchWidthMultiplier={2} // multiplied by the `circleSize` prop to calculate total width of the Switch
    switchBorderRadius={30} // Sets the border Radius of the switch slider. If unset, it remains the circleSize.
  />
)

Switch

switch

If this project was helpful to you, please Buy Me A Coffee

react-native-switch's People

Contributors

adamivancza avatar aidan-doherty avatar benomatis avatar binchik avatar darkrift avatar elliottkember avatar fattahmuhyiddeen avatar fuller avatar gevgasparyan avatar htbkoo avatar leecrossley avatar marneborn avatar paitoanderson avatar patrickkempff avatar pilotocheg avatar ralfnieuwenhuizen avatar rjerue avatar shahen94 avatar slavikmanukyan avatar stevegreenley avatar vasylnahuliak avatar vinics12 avatar vitorluizc avatar witodelnat avatar wkoutre 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-native-switch's Issues

Incompatibile with Expo SDK v22.0.0+

First of all, thanks for creating this component! :)
It provides much better flexibility to me than the native switch.

However, I believe that it is currently incompatible with the Expo SDK for version newer than v22.0.0 because of the usage of "View.propTypes.style".
The details are stated here in this expo blog:

If you, or any libraries that you use. use View.propTypes.style you will need to change that to ViewPropTypes.style. You will only see errors for this in production — so be sure to test your app with development mode disabled.

Locally I had tried to update accordingly and it worked for me.

Are there any plans to update this component?
I can create a pull request for this change if you do not mind. :)

Pass activeText as a object

from
{renderActiveText && ( <Text style={[styles.text, styles.paddingRight, activeTextStyle]}> activeText </Text> )}
to
{renderActiveText && ( <Text style={[styles.text, styles.paddingRight, activeTextStyle]}> {activeText} </Text> )}

Rendering activeText BUG

You have a bug in your code in Switch.js, line 215.
activeText needs brackets {activeText} otherwise it will always show 'activeText' string in the switch

Value prop not respected properly

I can't treat the switch as a controlled component. I have a component with value state and onValueChange method that are passed as props to the switch. If I set the value to false in the onValueChange, then do something before setting the value to true (or don't set it to true at all), the switch is in the visible on state even though value is false.

Example:

class Test extends Component {
  state = {
	value: false
  };

  onValueChange = (value: boolean) => {
	console.log(value);
	doSomeAsync((err) => {
	  if (err) {
		this.setState({ value: false });
	  } else {
		this.setState({ value });
	  }
	});
  }

  render() {
    const {
      state: { value },
      onValueChange
    } = this;

    return (
		<Switch
          value={value}
          onValueChange={onValueChange}
        />
    );
  }
}

No accessibility

Has come to my attention that Google TalkBack says nothing when turning off and on the switch.

Ideally, the change of state should be announced by the widget and even use the (in)activeText props for that.

React-native-web compatibility Issue

while running the app for web following issue is occuring.
web Failed to compile.
/node_modules/react-native-switch/lib/Switch.js
Module not found: Can't resolve 'react-native-web/dist/exports/ViewPropTypes' in '\node_modules\react-native-switch\lib'

Please merge this PR #87

The width of a switcher changes but the circle stays on it's place

Hello,
I am using the prop switchWidthMultiplier. The width of the bar changed but the circles did not move to the very end of the bar. It stayed on its previous place.
Attached the imagesa of the switcher, and the code.
Please help. Am I doing something wrong, or is it a bug?

react-native : 0.61.5
Device: Android Xiaomi
Your package version: 2.0.0

IMG_20200701_123726
IMG_20200701_123842
Swither

activeText is showing instead of the text we pass

Installed this npm using npm install --save react-native-switch. In my switch.js code was wrong. Change

            {renderActiveText && (
              <Text style={[styles.text, styles.paddingRight, activeTextStyle]}>
                activeText
              </Text>
            )}

to

            {renderActiveText && (
              <Text style={[styles.text, styles.paddingRight, activeTextStyle]}>
                {activeText}
              </Text>
            )}

in Switch.js

ive switch

When the value is reset, the switch is not updated

Not switching after first time switching

The issue I am having is that when I first use the switch, it remains in that state. So when I switch it to "Male", it won't allow me to switch back to "Female".

I use the sample code and the console, states "Male", even if I want to switch it "Female".

This is the code I am using:

<Switch 
    value={true}
    onValueChange={(val) => console.log(val)}
    disabled={false}
    activeText={I18n.t('male')}
    inActiveText={I18n.t('female')}
    backgroundActive={'green'}
    backgroundInactive={'gray'}
    circleActiveColor={'#30a566'}
    circleInActiveColor={'#000000'}
/>

Also tried it with "On" and "Off", same result.

Is this a bug?

Render Issue

Hi, I was using this lib on react native 0.50.3

The code

<View
                    style={{
                        margin: 24,
                        backgroundColor: 'blue',
                        height: 100,
                        justifyContent: 'center',
                        alignItems: 'center'
                    }}
                >
                    <Switch
                        value={true}
                        onValueChange={val => console.log(val)}
                        disabled={false}
                        activeText={'On'}
                        inActiveText={'Off'}
                        circleSize={30}
                        barHeight={1}
                        circleBorderWidth={3}
                        backgroundActive={'green'}
                        backgroundInactive={'gray'}
                        circleActiveColor={'#30a566'}
                        circleInActiveColor={'#000000'}
                    />
                </View>

But the switch shown is wierd

screen shot 2018-01-15 at 10 36 41 am
screen shot 2018-01-15 at 10 36 47 am

Rendering 'activeText' literal, not value on iOS

Using 1.5 ... the following code:

                <Switch
                  style={{ overflow: 'hidden' }}
                  value={this.state.alertsEnabled}
                  onValueChange={val => this.setState({ alertsEnabled: val })}
                  renderActiveText={this.state.alertsEnabled}
                  renderInActiveText={!this.state.alertsEnabled}
                  circleSize={35}
                  barHeight={25}
                  circleBorderWidth={0}
                  backgroundActive={'green'}
                  backgroundInactive={'gray'}
                  circleActiveColor={'#30a566'}
                  circleInActiveColor={'#000000'}
                  switchLeftPx={2} // denominator for logic when sliding to TRUE position. Higher number = more space from RIGHT of the circle to END of the slider
                  switchRightPx={2} // denominator for logic when sliding to FALSE position. Higher number = more space from LEFT of the circle to BEGINNING of the slider
                  switchWidthMultiplier={1.8} // multipled by the `circleSize` prop to calculate total width of the Switch
                />

produces
image

on iOS when switch is turned ON.

Off looks ok:

image

Any thoughts? Thanks!

Circle Animate doesn't happen when update disabled state

At the last version of project NPM, I checked a problem when I update the value and disabled props at the same time, animation of inside circle doesn't happen.
Probably, the problem is at Switch.js on the componentWillReceiveProps:

if (disabled) { return; }

Will work you change to:

if (disabled && disabled === nextProps.disabled) { return; }

NPM Outdated

NPM is outdated vs. the source.

There's also a bit of breakage as both default values have changed, notably renderActiveText: false, and renderInActiveText: false

active and inactive text is not showing in switch

I'm using below configuration for my switch but somehow active(On)/inactive(Off) text is not showing in switch.

                value={this.state.toggleStatus}
                onValueChange={this.switchToggler}
                disabled={false}
                activeText={"On"}
                inActiveText={"Off"}
                circleSize={25}
                barHeight={20}
                circleBorderWidth={0}
                backgroundActive={"#c9e099"}
                backgroundInactive={"#f4f4f4"}
                circleActiveColor={"#90bf2e"}
                circleInActiveColor={"lightgray"}
                changeValueImmediately={true}
/>

CircleBorderColor option is not there

There is option of circleBorderWidth but no option of circleBorderColor by default circleBorderWidth color is black we cant change it facing this issue

background color change in delay

Hi,
I tried the package but I noticed that the background color changes in delay of few seconds
is PanResponder that is commented should solve this issue?

switch with text

how can I do something like this, with your package:
image

the circle switches are ok.
But how can I do the textual switch, the selected value is blue and the unselected is white?

Thanks

React Native warning Animated: 'useNativeDriver'

Hi. I used the library recently, and jad no problem. But, when I used today, the React NAtive throws the warning for useNativeDriver. Do you resolve this in a new PR, or has a way in the props to do that?

Unable to resolve node_modules

I'm certain it's there, but I still have unable to resolve Module React from path/to/node_modules/react-native-switch/lib/Switch.js Unable to find this module in its module map or any of the node modules directory....

I've even tried removing the node_modules then reinstalling everything. Just to make sure...

Any ideas?
Thanks in advance... I've been looking all over for a switch like yours

In ios switch is not hiding off text

Specific issue with ios

Switch is look like

When switch is off, it looks like

screen shot 2017-02-27 at 11 43 23 am

When switch is on, it looks like

screen shot 2017-02-27 at 11 43 12 am

Off text is visible outside of switch

It is also visible in gif image that you provide, because background is white and text in also white it is not properly visible

screen shot 2017-02-27 at 11 46 34 am

Warning: Failed prop type: Invalid prop `activeTextStyle` of type `array` supplied to `Switch`, expected `object`

I know this warning is being shown as PropTypes of style props are set to object and I used an array (as is common in React Native to define styles), but the interesting thing is that the styles I applied this way would still work.

I first thought I'd just submit a PR and turn this...

activeTextStyle: PropTypes.object,

...into this...

activeTextStyle: PropTypes.oneOfType([
  PropTypes.object,
  PropTypes.array
]),

...but I was wondering if it would actually cause issues as it's being used like this further down:

<Text style={[styles.text, styles.paddingRight, activeTextStyle]}>
{activeText}
</Text>

Unable to render Custom component inside switch

This is my code. It is not showing the check-circle image in between the switch circle.

  _renderSwitch = () => {
        return (<Switch
            value={this.props.value}
            onValueChange={(value) => this.props.onToggleSwitchPress()}
            disabled={false}
            circleSize={30}
            changeValueImmediately={true}
            renderInsideCircle={this._renderCheckMark} // custom component to render inside the Switch circle (Text, Image, etc.)
            changeValueImmediately={true} // if rendering inside circle, change state immediately or wait for animation to complete
            innerCircleStyle={{ alignItems: "center", justifyContent: "center" }} // style for inner animated circle for what you (may) be rendering inside the circle
            outerCircleStyle={{}} // style for outer animated circle
            switchLeftPx={2} // denominator for logic when sliding to TRUE position. Higher number = more space from RIGHT of the circle to END of the slider
            switchRightPx={2} // denominator for logic when sliding to FALSE position. Higher number = more space from LEFT of the circle to BEGINNING of the slider
            switchWidthMultiplier={2} // multipled by the `circleSize` prop to calculate total width of the Switch
        />);
    }    

    _renderCheckMark = () => {
        <UaView style={{backgroundColor:"red"}}>
           <MaterialIcon name={"check-circle"} color={"success"} size="medium" style={styles.icon} /> 
        </UaView>
    }

Circle border color

For the moment the border color for circle can't be changed, is it possible to be implemented a change for this?

[Feature] Reduce the number of props

I've noticed that you used many properties though there are ones that can be reduced in one property.

Current

<Switch
    backgroundActive={'green'}
    backgroundInactive={'gray'}
  />

Suggested

<Switch
    background={active:'green',inActive:'gray'}
  />

onValueChange called after animation completion

Right now onValueChange is called after animation completes. I think it would be better if it was called on switch press. In my app I make some UI mutations when user changes switch's value and it would feel much more performant if the mutations started early.

I installed with yarn install but type update did not work

I installed the library with yarn install ... but the type config did not come the index.d.ts and json modification, I did on my own the modification, but for other developers that would break the project that is in Typescript, can you please check

Proptypes completely removed

PropTypes has been moved to a separate package. Accessing React.PropTypes is no longer supported and will be removed completely in React 16. Use the prop-types package on npm instead.

NPM package outdated

The NPM package is an old version without the circleBorderColor prop included.

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.