Created
February 28, 2018 14:59
-
-
Save andrewkslv/0763e19e494e09e6f80031b7caa60792 to your computer and use it in GitHub Desktop.
React Native animation without goes outside of the screen
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import { View, StyleSheet, Animated, Dimensions } from 'react-native'; | |
const { width, height } = Dimensions.get('window'); | |
const BOX_DIM = 50; | |
export default class App extends Component { | |
componentWillMount() { | |
this.animation = new Animated.ValueXY(0); | |
} | |
componentDidMount() { | |
Animated.parallel([ | |
Animated.timing(this.animation.x, { | |
toValue: width * 2, | |
}), | |
Animated.timing(this.animation.y, { | |
toValue: height * 2, | |
}), | |
]).start(); | |
} | |
render() { | |
const widthRange = [0, width - BOX_DIM]; | |
const heightRange = [0, height - BOX_DIM]; | |
const xAnimation = this.animation.x.interpolate({ | |
inputRange: widthRange, | |
outputRange: widthRange, | |
extrapolate: 'clamp', | |
}); | |
const yAnimation = this.animation.y.interpolate({ | |
inputRange: heightRange, | |
outputRange: heightRange, | |
extrapolate: 'clamp', | |
}); | |
const moveStyle = { | |
transform: [ | |
{ | |
translateX: xAnimation, | |
}, | |
{ | |
translateY: yAnimation, | |
}, | |
], | |
}; | |
return ( | |
<View style={styles.container}> | |
<Animated.View style={[styles.box, moveStyle]} /> | |
</View> | |
); | |
} | |
} | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, | |
}, | |
box: { | |
height: BOX_DIM, | |
width: BOX_DIM, | |
backgroundColor: 'tomato', | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment