Can I cause React Native's Switch component to animate when changing its state when not being directly pressed by the user?

Viewed 1985

In my React Native project I'm using the Switch component. It can be switched directly by pressing it, but I also want to let the user change it by pressing nearby related items.

It of course animates the switching when pressed, but when I changed its state using setState() it just jumps directly to the other position without animation.

Is there a way I can programmatically trigger the animation when changing its state from code?

(There is a question with a similar wording but it seems to be to an unrelated problem I can't quite work out.)

1 Answers

Depends a little on the approach you're taking, but I'd say your best bet is with Animated (which is part of React Native).

You can do something like this:

render(){
    var animVal = new Animated.Value(0);   
    Animated.timing(animVal, {toValue: 1, duration: 300}).start();
    var animatedViewStyles =
        {
             marginLeft: animVal.interpolate({
                 inputRange: [0, 1],
                 outputRange: this.state.switchOn ? [100, 0] : [0, 100],
             }),
             // add some other styles here
             color: 'green'
        };
    }

    return (
        <Animated.View style={animatedViewStyles}>
            <TouchableHighlight onPress(() => this.setState({switchOn: !this.state.switchOn}))><Text>This is my switch</Text></TouchableHighlight>
        </Animated.View>
    );

See the docs https://facebook.github.io/react-native/docs/animated.html for more info.

Related