Skip to content

Instantly share code, notes, and snippets.

@likern
Last active August 13, 2023 02:25
Show Gist options
  • Save likern/acc19a0cd8777a170dbcebdb873730c1 to your computer and use it in GitHub Desktop.
Save likern/acc19a0cd8777a170dbcebdb873730c1 to your computer and use it in GitHub Desktop.
React Native Opacity Animation Example
import React, { useState } from 'react';
import { useMemoOne } from 'use-memo-one';
import { View, Button } from 'react-native';
import Animated, {
cond,
not,
clockRunning,
startClock,
interpolate,
Extrapolate,
add,
stopClock,
eq,
debug
} from 'react-native-reanimated';
const { Value, Clock, useCode, set, block } = Animated;
const duration = 4000;
const Application = () => {
const [show, setShow] = useState(false);
const { time, clock, progress } = useMemoOne(
() => ({
time: new Value(0),
clock: new Clock(),
progress: new Value(0)
}),
[]
);
const opacity = interpolate(progress, {
inputRange: [0, 1],
outputRange: show ? [0, 1] : [1, 0],
extrapolate: Extrapolate.CLAMP
});
useCode(() => debug('progress is', opacity), [opacity]);
useCode(
() =>
block([
cond(not(clockRunning(clock)), [startClock(clock), set(time, clock)]),
set(
progress,
interpolate(clock, {
inputRange: [time, add(time, duration)],
outputRange: [0, 1],
extrapolate: Extrapolate.CLAMP
})
),
cond(eq(progress, 1), stopClock(clock))
]),
[]
);
return (
<View>
<Animated.View style={{ opacity }}>
<View style={{ width: 300, height: 300, backgroundColor: 'red' }} />
</Animated.View>
<View
css={`
margin-top: 100px;
`}
>
<Button title='Toggle opacity' onPress={() => setShow(prev => !prev)} />
</View>
</View>
);
};
export default Application;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment