Skip to content

Instantly share code, notes, and snippets.

@mmazzarolo
Created November 13, 2019 13:08
Show Gist options
  • Save mmazzarolo/d78beafedc790fd31d35afef195f5a3d to your computer and use it in GitHub Desktop.
Save mmazzarolo/d78beafedc790fd31d35afef195f5a3d to your computer and use it in GitHub Desktop.
Animate React-Native components based on MobX observables changes
import { useEffect, useState } from "react";
import { Animated, Text, View } from "react-native";
import { reaction } from "mobx";
import { observer } from "mobx-react";
const defaultCheckObservedValue = observed => observed.visible;
const defaultCreateAnimationIn = animValue =>
Animated.timing(animValue, {
toValue: 1,
useNativeDriver: true
});
const defaultCreateAnimationOut = animValue =>
Animated.timing(animValue, {
toValue: 0,
useNativeDriver: true
});
const defaultCreateAnimatedStyle = animValue => ({
transform: [{ scale: animValue }]
});
export const useObservableAnimation = function({
observed, // The observed item
checkObservedValue = defaultCheckObservedValue,
createAnimationIn = defaultCreateAnimationIn,
createAnimationOut = defaultCreateAnimationOut,
createAnimatedStyle = defaultCreateAnimatedStyle
}) {
const [animValue] = useState(
new Animated.Value(checkObservedValue(observed))
);
useEffect(() => {
return reaction(
() => checkObservedValue(observed),
shouldAnimate => {
if (shouldAnimate) {
createAnimationIn(animValue).start();
} else {
createAnimationOut(animValue).start();
}
}
);
}, []);
return createAnimatedStyle(animValue);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment