Git Product home page Git Product logo

switch-button-react-native's Introduction

switch-button-react-native

Customisable switch button in react native ( e.g: change view after change switch button )

switchbutton

how to use:

  1. import component

  2. set

     activeSwitch=1
    

to state

  1. use:

     <SwitchButton  
           onValueChange={(val) => this.setState({ activeSwitch: val })} 
     /> 
    

in your code

  1. use:

     { this.state.activeSwitch === 1 ? view1 : view2 }
    

small example: ...

import React, { Component } from 'react'; 
import { View } from 'react-native'; 
import SwitchButton from 'switch-button-react-native';

constructor () {
    super();

    this.state = {
      activeSwitch: 1
    };
}


render () {

    return (

        <View>
            <SwitchButton
                onValueChange={(val) => this.setState({ activeSwitch: val })}      // this is necessary for this component
                text1 = 'ON'                        // optional: first text in switch button --- default ON
                text2 = 'OFF'                       // optional: second text in switch button --- default OFF
                switchWidth = {100}                 // optional: switch width --- default 44
                switchHeight = {44}                 // optional: switch height --- default 100
                switchdirection = 'rtl'             // optional: switch button direction ( ltr and rtl ) --- default ltr
                switchBorderRadius = {100}          // optional: switch border radius --- default oval
                switchSpeedChange = {500}           // optional: button change speed --- default 100
                switchBorderColor = '#d4d4d4'       // optional: switch border color --- default #d4d4d4
                switchBackgroundColor = '#fff'      // optional: switch background color --- default #fff
                btnBorderColor = '#00a4b9'          // optional: button border color --- default #00a4b9
                btnBackgroundColor = '#00bcd4'      // optional: button background color --- default #00bcd4
                fontColor = '#b1b1b1'               // optional: text font color --- default #b1b1b1
                activeFontColor = '#fff'            // optional: active font color --- default #fff
            />
            
            { this.state.activeSwitch === 1 ? console.log('view1') : console.log('view2') }
            
        </View>

    );
}

switch-button-react-native's People

Contributors

sramezani 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

Watchers

 avatar

switch-button-react-native's Issues

Translated to TypeScript and added props

Hey, I've translated your code to TypeScript and simplified it in the process.
I've also added a couple of extra Props: fontFamily, fontSize, switchMargin which was hardcoded to 6, btnBorderWidth which was hardcoded to 1 and btnBorderRadius which was hardcoded to switchBorderRadius.
Feel free to test it and/or merge it into your repo.
Thanks for your work!

import React, { Component } from "react";
import {
	View,
	Text,
	TouchableWithoutFeedback,
	StyleSheet,
	Animated,
} from "react-native";

type Props = {
	onValueChange: (activeSwitch: 1 | 2) => void;
	fontFamily?: string;
	fontSize?: number;
} & typeof SwitchButton.defaultProps;

interface State {
	offsetX: Animated.Value;
}

class SwitchButton extends Component<Props, State> {
	static defaultProps = {
		text1: "ON",
		text2: "OFF",

		activeSwitch: 1 as 1 | 2,

		switchWidth: 100,
		switchHeight: 44,
		switchMargin: 6,
		switchBorderRadius: 22,
		switchBorderColor: "#d4d4d4",
		switchBackgroundColor: "#fff",
		switchBorderWidth: 1,

		changeSpeed: 100,

		fontColor: "#b1b1b1",
		activeFontColor: "#fff",

		btnBorderColor: "#00a4b9",
		btnBorderWidth: 1,
		btnBorderRadius: 22,
		btnBackgroundColor: "#00bcd4",

		direction: "ltr" as "ltr" | "rtl",
	};

	constructor(props: Props) {
		super(props);
		this.state = {
			offsetX: new Animated.Value(
				this.props.activeSwitch === 1
					? this.getOffsetXFor1()
					: this.getOffsetXFor2()
			),
		};
	}

	componentWillReceiveProps = (nextProps: Props) => {
		if (this.props.activeSwitch !== nextProps.activeSwitch) {
			this.animate();
		}
	};

	getOffsetXFor1 = () => {
		return this.props.switchMargin;
	};

	getOffsetXFor2 = () => {
		const { switchWidth, switchMargin, direction } = this.props;
		let dirsign = 1;
		if (direction === "rtl") {
			dirsign = -1;
		}
		return (switchWidth / 2 + switchMargin) * dirsign;
	};

	switchThump = () => {
		const { onValueChange } = this.props;

		if (this.props.activeSwitch === 1) {
			onValueChange(2);
		} else {
			onValueChange(1);
		}
	};

	animate = () => {
		const { activeSwitch, changeSpeed } = this.props;
		if (activeSwitch === 1) {
			Animated.timing(this.state.offsetX, {
				toValue: this.getOffsetXFor2(),
				duration: changeSpeed,
			}).start();
		} else {
			Animated.timing(this.state.offsetX, {
				toValue: this.getOffsetXFor1(),
				duration: changeSpeed,
			}).start();
		}
	};

	render = () => (
		<TouchableWithoutFeedback onPress={this.switchThump}>
			<View
				style={{
					width: this.props.switchWidth,
					height: this.props.switchHeight,
					borderRadius: this.props.switchBorderRadius,
					borderWidth: this.props.switchBorderWidth,
					borderColor: this.props.switchBorderColor,
					backgroundColor: this.props.switchBackgroundColor,
				}}
			>
				<View
					style={
						this.props.direction === "ltr" ? switchStyles.ltr : switchStyles.rtl
					}
				>
					<Animated.View
						style={{
							transform: [{ translateX: this.state.offsetX }],
							top: this.props.switchMargin,
						}}
					>
						<View
							style={{
								width: this.props.switchWidth / 2 - 2 * this.props.switchMargin,
								height: this.props.switchHeight - 2 * this.props.switchMargin,
								borderWidth: this.props.btnBorderWidth,
								borderRadius: this.props.btnBorderRadius,
								borderColor: this.props.btnBorderColor,
								backgroundColor: this.props.btnBackgroundColor,
							}}
						/>
					</Animated.View>

					<View
						style={[
							switchStyles.textPos,
							{
								width: this.props.switchWidth / 2,
								height: this.props.switchHeight,
								left: 0,
							},
						]}
					>
						<Text
							style={{
								fontFamily: this.props.fontFamily,
								fontSize: this.props.fontSize,
								textAlign: "center",
								color:
									this.props.activeSwitch === 1
										? this.props.activeFontColor
										: this.props.fontColor,
							}}
						>
							{this.props.text1}
						</Text>
					</View>

					<View
						style={[
							switchStyles.textPos,
							{
								width: this.props.switchWidth / 2,
								height: this.props.switchHeight,
								right: 0,
							},
						]}
					>
						<Text
							style={{
								fontFamily: this.props.fontFamily,
								fontSize: this.props.fontSize,
								textAlign: "center",
								color:
									this.props.activeSwitch === 2
										? this.props.activeFontColor
										: this.props.fontColor,
							}}
						>
							{this.props.text2}
						</Text>
					</View>
				</View>
			</View>
		</TouchableWithoutFeedback>
	);
}

const switchStyles = StyleSheet.create({
	textPos: {
		position: "absolute",
		justifyContent: "center",
		alignItems: "center",
	},
	rtl: {
		flexDirection: "row-reverse",
	},
	ltr: {
		flexDirection: "row",
	},
});

export default SwitchButton;

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.