Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate when pressed in react-native animated

Tags:

react-native

I would like to animate a view on press.

export default class AnimatedRotation extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            spinValue: new Animated.Value(0),
            color: '#F62459',
        }
    }

    rotateSpring = () => {
        Animated.spring(
            this.state.spinValue,
            {
                toValue: 1,
                friction: 1,
            }
        ).start();
        this.setState({
            color: this.state.color == '#F62469' ? '#FFC107' : '#F62469',
        })
    };

    render() {
        var spin = this.state.spinValue.interpolate({
            inputRange: [0, 1],
            outputRange: ['0deg', '360deg'],
        });

        return (
            <View style={styles.container}>
                <Text style={styles.header}>Header</Text>
                <View style={styles.wrapper}>
                    <TouchableWithoutFeedback onPress={this.rotateSpring}>
                        <Animated.View style={[styles.circle, {
                            transform: [{rotate: spin},],
                            backgroundColor: this.state.color
                            }]}>
                            <Icon name="ios-add" color="white" size={50}/>
                        </Animated.View>
                    </TouchableWithoutFeedback>
                </View>
            </View>
        );
    }
}

But when I press its animating only once, and not animating again. I suppose its because, the state of spinValue equals to the toValue when its pressed for the first time. So I thought of doing something like this:

rotateSpring = () => {
    Animated.spring(
        this.state.spinValue,
        {
            toValue: this.state.spinValue + 1,
            friction: 1,
        }
    ).start();
    this.setState({
        color: this.state.color == '#F62469' ? '#FFC107' : '#F62469',
        spinValue: this.state.spinValue + 1,
    })
};

But this makes the app crash. How do I animate something onPress?

like image 741
Kakar Avatar asked Oct 30 '22 13:10

Kakar


1 Answers

Very simple solution:

this.state.spinValue.setValue(0);
Animated.spring(...);

If your animation is cyclic (and it looks like it is) then you should be fine with simply running this line before starting the animation.

Comment: There's no reason for the Animated.Value to be a part of the state. A good hint for that is the fact that you never used setState() with it.

like image 123
Dror Aharon Avatar answered Nov 03 '22 00:11

Dror Aharon