Sara
Sara

Reputation: 103

Making animation continuous in react native

Here I am animating an icon but I need it to continuously spin. I am able to get it to spin but it stops. I'm not sure how to change it so that it continuously spins. It will spin for bit but it won't spin continuously.

import React, { useRef } from 'react';
import { Animated, Easing, StyleProp, TextStyle } from 'react-native';
import useMountEffect from '../../../common/hook/useMountEffect';
import Icon from '../../../common/icon/Icon/Icon';

interface Props {
  name: string;
  size?: number;
  color?: string;
  style?: StyleProp<TextStyle>;
  variant?: 'solid' | 'brand' | 'light';
}

const SpinningIcon: React.FC<Props> = ({
  name,
  size,
  color,
  style,
  variant,
}) => {
  const spinValue = useRef(new Animated.Value(0));
  useMountEffect(() => {
    Animated.timing(spinValue.current, {
      toValue: 1,
      duration: 1000,
      easing: Easing.linear,
      useNativeDriver: true,
    }).start();
  });

  const rotate = spinValue.current.interpolate({
    inputRange: [0, 1],
    outputRange: ['0deg', '360deg'],
  });

  return (
    <Animated.View style={{ transform: [{ rotate }] }}>
      <Icon
        size={size}
        color={color}
        name={name}
        style={style}
        variant={variant}
      />
    </Animated.View>
  );
};

export default SpinningIcon;

Upvotes: 0

Views: 594

Answers (1)

Iosif
Iosif

Reputation: 822

You can use Animated.loop()

import React, { useRef } from 'react';
import { Animated, Easing, StyleProp, TextStyle } from 'react-native';
import useMountEffect from '../../../common/hook/useMountEffect';
import Icon from '../../../common/icon/Icon/Icon';

interface Props {
  name: string;
  size?: number;
  color?: string;
  style?: StyleProp<TextStyle>;
  variant?: 'solid' | 'brand' | 'light';
}

const SpinningIcon: React.FC<Props> = ({
  name,
  size,
  color,
  style,
  variant,
}) => {
  const spinValue = useRef(new Animated.Value(0));
  useMountEffect(() => {
    Animated.loop(
      Animated.timing(spinValue.current, {
        toValue: 1,
        duration: 1000,
        easing: Easing.linear,
        useNativeDriver: true,
      }),
    ).start();
  });

  const rotate = spinValue.current.interpolate({
    inputRange: [0, 1],
    outputRange: ['0deg', '360deg'],
  });

  return (
    <Animated.View style={{ transform: [{ rotate }] }}>
      <Icon
        size={size}
        color={color}
        name={name}
        style={style}
        variant={variant}
      />
    </Animated.View>
  );
};

export default SpinningIcon;

Upvotes: 2

Related Questions