Skip to content

Instantly share code, notes, and snippets.

@andrewkslv
Created February 28, 2018 14:59
Show Gist options
  • Save andrewkslv/0763e19e494e09e6f80031b7caa60792 to your computer and use it in GitHub Desktop.
Save andrewkslv/0763e19e494e09e6f80031b7caa60792 to your computer and use it in GitHub Desktop.
React Native animation without goes outside of the screen
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