Skip to content

Instantly share code, notes, and snippets.

@faceyspacey
Last active September 18, 2016 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save faceyspacey/39575d1b807f219a18cdd86ad274dc15 to your computer and use it in GitHub Desktop.
Save faceyspacey/39575d1b807f219a18cdd86ad274dc15 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import {
Text,
View,
Image,
Animated,
Easing,
} from 'react-native';
const ALL_PROPERTIES = ['translateX', 'translateY', 'translateZ', 'rotateX', 'rotateY', 'rotateZ', 'scale'];
export class AnimatedView extends Component {
constructor(props, context) {
super(props, context);
this.properties = [];
ALL_PROPERTIES.forEach((prop) => {
if(typeof props[prop] !== 'undefined') {
this.properties.push(prop);
this[prop] = new Animated.Value(props[prop]);
}
});
}
shouldComponentUpdate(nextProps) {
let shouldUpdate = true;
this.properties.forEach((prop) => {
if(this.props[prop] !== nextProps[prop]) {
shouldUpdate = false;
this.animate(this[prop], nextProps[prop], nextProps);
}
});
return shouldUpdate;
}
animate(animatedValue, toValue, {duration, easing}) {
Animated.timing(animatedValue, {
toValue,
duration: duration || 300,
easing: easing ? Easing[easing] : Easing.sin
}).start();
}
getTransform() {
return this.properties.map((prop) => {
let animatedValue = this[prop];
if(prop.indexOf('rotate') === 0) {
animatedValue = animatedValue.interpolate({
inputRange: [-360, 0, 360],
outputRange: ['-360deg', '0deg', '360deg'],
});
}
return {
[prop]: animatedValue
};
});
}
render() {
let {children, duration, easing, style, ...props} = this.props;
let transform = this.getTransform();
ALL_PROPERTIES.forEach((prop) => {
delete props[prop];
});
return (
<Animated.View {...props} style={[style, {transform}]}>
{children}
</Animated.View>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment