How to add shake animation to a view (react-native)?

Here is the shake animation for Image component in react native, you can check it-

const bgImage = require('./components/images/ex.jpg')

class App extends Component {

   constructor(props) {
     super(props)
     this.animatedValue = new Animated.Value(0)
   }

   handleAnimation = () => {
   // A loop is needed for continuous animation
   Animated.loop(
     // Animation consists of a sequence of steps
     Animated.sequence([
       // start rotation in one direction (only half the time is needed)
       Animated.timing(this.animatedValue, {toValue: 1.0, duration: 150, easing: Easing.linear, useNativeDriver: true}),
       // rotate in other direction, to minimum value (= twice the duration of above)
       Animated.timing(this.animatedValue, {toValue: -1.0, duration: 300, easing: Easing.linear, useNativeDriver: true}),
       // return to begin position
       Animated.timing(this.animatedValue, {toValue: 0.0, duration: 150, easing: Easing.linear, useNativeDriver: true})
     ])
   ).start(); 
   }
 }

To add this Animation to Image Component-

<Animated.Image
  source={bgImage}
  resizeMode='contain'
  style={{
    transform: [{
    rotate: this.animatedValue.interpolate({
       inputRange: [-1, 1],
       outputRange: ['-0.1rad', '0.1rad']
      })
    }]
  }}
/>

Thank you for all answers.

I just solved editing my code with the following code

  constructor(props) {
    super(props)
    this.shakeAnimation = new Animated.Value(0);
  }

 startShake = () => {
    Animated.sequence([
      Animated.timing(this.shakeAnimation, { toValue: 10, duration: 100, useNativeDriver: true }),
      Animated.timing(this.shakeAnimation, { toValue: -10, duration: 100, useNativeDriver: true }),
      Animated.timing(this.shakeAnimation, { toValue: 10, duration: 100, useNativeDriver: true }),
      Animated.timing(this.shakeAnimation, { toValue: 0, duration: 100, useNativeDriver: true })
    ]).start();
 }

 <Animated.View style={{ transform: [{translateX: this.shakeAnimation}] }}>  

 </Animated.View>

Tags:

React Native