shogitai
shogitai

Reputation: 1961

How to use React Native Switch inside a functional component?

I am trying to use the Switch component provided by react-native, but it doesn't toggle.

function settings(props) {
    let {changeView, header} = props;
    let rememberPin = false;
    let toggleRememberPin = (value) => {
        rememberPin = value;
    };
    return (
        <View style={styles.appContainer}>
            <View style={styles.appBody}>
                <View style={{flex:1, flexDirection: 'row',justifyContent:'center',alignItems:'center',width: Dimensions.get('screen').width,backgroundColor: Colors.white}}>
                    <Text>Remember PIN:</Text>
                    <Switch
                        onValueChange={toggleRememberPin}
                        value={rememberPin}
                        ios_backgroundColor="#aeaeae"
                        trackColor={{true: Colors.customerGreen, false: '#aeaeae',}}/>
                </View>
            </View>
        </View>
    );
}

I get the Switch rendered in the View, I can touch it and it moves from OFF to ON, but suddently it come back to OFF without keeping on ON state.

What's wrong?

Upvotes: 0

Views: 1391

Answers (1)

emeraldsanto
emeraldsanto

Reputation: 4741

You need to look into the core concepts of React, particularly how component state works.

In short, normal variable assignment doesn't cause a component to re-render and reflect changes. That's when you want to use the concept of state.

Here's how to do it properly:

function Settings(props) {
    let {changeView, header} = props;
    const [rememberPin, setRememberPin] = useState(false);

    const toggleRememberPin = (value) => {
        setRememberPin(value);
    };

    return (
        <View style={styles.appContainer}>
            <View style={styles.appBody}>
                <View style={{flex:1, flexDirection: 'row',justifyContent:'center',alignItems:'center',width: Dimensions.get('screen').width,backgroundColor: Colors.white}}>
                    <Text>Remember PIN:</Text>
                    <Switch
                        onValueChange={toggleRememberPin}
                        value={rememberPin}
                        ios_backgroundColor="#aeaeae"
                        trackColor={{true: Colors.customerGreen, false: '#aeaeae',}}/>
                </View>
            </View>
        </View>
    );
}

Upvotes: 2

Related Questions