Created
November 13, 2019 13:08
-
-
Save mmazzarolo/d78beafedc790fd31d35afef195f5a3d to your computer and use it in GitHub Desktop.
Animate React-Native components based on MobX observables changes
This file contains hidden or 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 { 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