PanGestureHandler with functional component react native - react-native

I am trying to use a Gesture handler with a functional component. The problem is when I drag for the second time it's dragging from initial position again
This is my code below
let translateXRef = useRef(new Animated.Value(0)).current;
const onGestureEvent = useCallback(
Animated.event(
[
{
nativeEvent: {
translationX: translateXRef,
},
},
],
{ useNativeDriver: true }
),
[]
);
<View
style={{
backgroundColor: '#FFFFFF80',
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
height: 100,
}}
>
<PanGestureHandler
onGestureEvent={onGestureEvent}
onHandlerStateChange={onHandlerStateChange}
>
<Animated.View
// eslint-disable-next-line react-native/no-inline-styles
style={{
height: '100%',
width: 10,
backgroundColor: AppColors.buttonColor,
transform: [{ translateX: translateXRef }],
}}
/>
</PanGestureHandler>
</View>

You need to use the context in addition to the event in your callback.
I'm not sure why you're using the Animated.event. You should generate your callbacks using the useAnimatedGestureHandler.
Each of those callbacks onStart, onActive, onEnd, etc... take an event and context argument.
The context argument is an object that would let you set your previous position so that then next click would not reset the position.
Here's more info:
https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/events/#using-context
Also, a pretty good video that explains it:
https://youtu.be/4HUreYYoE6U

Related

How to add starting animation delay to lottie-react-native

This is my component and I want the animation to start 0.5s after the page has been landed on. How can I achieve this?
No props for delay here:
https://github.com/lottie-react-native/lottie-react-native/
<Lottie
style={[
{
position: 'relative',
height: 160,
width: 160,
},
spacing.gbMt1,
]}
autoPlay={true}
loop={false}
source={require('../assets/lottie/Coach001.json')}
/>
There is no prop for adding time delay but you can use these API methods to play, pause, resume and reset animation. You will need to set autoplay to false and call "play" method in timeout of 5 seconds to achieve the required delay.
useEffect(() => {
setTimeout(() => {
ref?.current?.play();
}, 500)
}, [])
<Lottie
ref={ref}
style={[
{
position: 'relative',
height: 160,
width: 160,
},
spacing.gbMt1,
]}
autoPlay={false}
loop={false}
source={require('../assets/lottie/Coach001.json')}
/>

Add gradient to Navigation Container in React Native App

I've been trying to add a linear gradient as a background to my react native app.
Here is my initial code:
<NavigationContainer theme={MyTheme}>
<Stack.Navigator
initialRouteName="Camera"
screenOptions={{
headerStyle: { elevation: 0 },
}}
>
And here my attempt at adding the gradient:
const MyTheme = {
colors: {
primary: "rgb(255, 45, 85)",
background: () => <LinearGradient colors={["red", "blue"]} />,
},
};
Now, when I console.log(MyTheme.colors) I get background: [Function background
Any idea how I can make this work?
You can try this, may help below code.
<LinearGradient
colors={["red", "blue"]}
start={{x: "Your postition", y: "Your postition"}}
end={{x: "Your postition", y: "Your postition"}}
/>
<View style={{flex:1}}>
<LinearGradient style={{ position: "absolute",
left:0,right: 0, top: 0,bottom: 0,
}}
colors={["#120318", "#221a36"]}
/>
</View>
If you set the LinearGradient's position to absolute, and set left,right,top,bottom as 0, LinearGradient will take up entire space's of its parent element.

How to animate header to show based on scrolling in react native?

So Ideally, When i scroll down, I want the header to disappear(slide down) and when I scroll up I want it to show (slide up). Idc where im at in the page. I just want the animation to fire when those 2 events occur. I see some apps have this but I can't think of how to replicate it. please help me set a basis for this
You can use Animated.FlatList or Animated.ScrollView to make the scroll view, and attach a callback to listen onScroll event when it is changed. Then, using interpolation to map value between y-axis and opacity.
searchBarOpacityAnim is a component's state. By using Animated.event, the state will be updated when a callback is called. Also, don't forget to set useNativeDriver to be true. I've attached the link to document below about why you have to set it.
<Animated.FlatList
...
onScroll={Animated.event(
[{ nativeEvent: { contentOffset: { y: searchBarOpacityAnim } } }],
{ useNativeDriver: true },
)}
...
/>
Then, use Animated.View wraps your component which you want to animate it. Use .interpolate to map value between the state and component's opacity like the example below...
<Animated.View
style={{
opacity: searchBarOpacityAnim.interpolate({
inputRange: [213, 215],
outputRange: [0, 1],
}),
}}
>
<SearchBar />
</Animated.View>
You can read more information about useNativeDriver, .interpolate, and Animated.event here.
https://facebook.github.io/react-native/docs/animated#using-the-native-driver
https://facebook.github.io/react-native/docs/animations#interpolation
https://facebook.github.io/react-native/docs/animated#handling-gestures-and-other-events
You can use Animated from 'react-native'
here an example changing the Topbar height:
import { Animated } from 'react-native';
define maxHeight and minHeight topbar
const HEADER_MAX_HEIGHT = 120;
const HEADER_MIN_HEIGHT = 48;
initialize a variable with the scrollY value
constructor(props) {
super(props);
this.state = {
scrollY: new Animated.Value(
Platform.OS === 'ios' ? -HEADER_MAX_HEIGHT : 0,
),
};
}
on render you can interpolate a value acording the scrollY Value
render() {
const { scrollY } = this.state;
// this will set a height for topbar
const headerHeight = scrollY.interpolate({
inputRange: [0, HEADER_MAX_HEIGHT - HEADER_MIN_HEIGHT],
outputRange: [HEADER_MAX_HEIGHT, HEADER_MIN_HEIGHT],
extrapolate: 'clamp',
});
// obs: the inputRange is the scrollY value, (starts on 0)
// and can go until (HEADER_MAX_HEIGHT - HEADER_MIN_HEIGHT)
// outputRange is the height that will set on topbar
// obs: you must add a onScroll function on a scrollView like below:
return (
<View>
<Animated.View style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
backgroundColor: '#2e4265',
height: headerHeight,
zIndex: 1,
flexDirection: 'row',
justifyContent: 'flex-start',
}}>
<Text>{title}</Text>
</Animated.View>
<ScrollView
style={{ flex: 1 }}
scrollEventThrottle={16}
onScroll={Animated.event(
[{ nativeEvent: { contentOffset: { y: this.state.scrollY } } }],
)}>
<View style={{ height: 1000 }} />
</ScrollView>
</View>
);
}

get rid of border in Card Component React native element

In the Card Component for react native elements
I'm trying to get rid of the border by setting the border to 0 and borderColor to transparent but there's still a gray outline
<Card
containerStyle={{borderWidth: 0, borderColor: 'transparent', elevation: 0}}
title='HELLO WORLD'
image={require('../images/pic2.jpg')}>
<Text style={{marginBottom: 10}}>
The idea with React Native Elements is more about component structure than actual design.
</Text>
</Card>
Thought it might have been box shadow, but that's not it either
I've got the same issue, and I've found that border appears because the Card element has an elevation default setted to 1
You can override this (for android) :
<Card containerStyle={{elevation:0, backgroundColor:#123}}/>
and in IOS:
const styles = {
container: {
shadowColor: 'rgba(0,0,0, .2)',
shadowOffset: { height: 0, width: 0 },
shadowOpacity: 0, //default is 1
shadowRadius: 0//default is 1
}
}
<Card containerStyle={styles.container} />
Its late but it seems that a lot of people still searching for the Answer.
React Native Elements by default have set both borderWidth and shadow Props, so in order to remove border completely you need to remove both Border and Shadow.
<Card containerStyle={styles.cardCnt}>
<Text>Content</Text>
</Card>
const styles = {
cardCnt: {
borderWidth: 0, // Remove Border
shadowColor: 'rgba(0,0,0, 0.0)', // Remove Shadow for iOS
shadowOffset: { height: 0, width: 0 },
shadowOpacity: 0,
shadowRadius: 0,
elevation: 0 // Remove Shadow for Android
}
};
It looks like react native elements' Card component has a grey border in all of the examples I've seen. I'd suggest building your own card component. Start with something like this and then style it however you want. This one has a bit of shadow which you can turn off by passing it a noShadow prop.
import React from 'react';
import { View, StyleSheet } from 'react-native';
const Card = (props) => {
let shadowStyle = {
shadowColor: COLORS.grey3,
shadowOffset: { width: 0, height: 0 },
shadowOpacity: .5,
shadowRadius: 12,
elevation: 1,
}
if (props.noShadow) {
shadowStyle = {}
}
return (
<View style={[styles.containerStyle, props.style, shadowStyle]}>
{props.children}
</View>
);
};
const styles = StyleSheet.create({
containerStyle: {
padding: 10,
marginHorizontal: 10,
backgroundColor: COLORS.white,
borderRadius: 3,
}
})
export { Card };
Then when you want to use it just
import { Card } from './yourCustomCardFile'
Then in your render method
<Card>
<Text>Any content you want to include on the card</Text>
<Text>More content that you want on the card</Text>
</Card>
set elevation to 0 and borderColor to white like this
<Card containerStyle={{ elevation: 0, borderColor: "white" }}>
set to screen background color
Dirty but problem solved.

How to make a looped image background in React Native with Animated

I originally used setInterval() to make a looped image background by having two images that one starts at x:0 and another starts at x: imageWidth, then update them in the following way:
_updateBackgroundImage = () => {
this.setState({
background1Left: this.state.background1Left > (-this.backgroundImageWidth) ? this.state.background1Left-3 : this.backgroundImageWidth,
background2Left: this.state.background2Left > (-this.backgroundImageWidth) ? this.state.background2Left-3 : this.backgroundImageWidth,
})
}
It worked just fine but setInterval() was causing conflicts with another component from an online library, so I switched to using Animated API and have the following code:
this.translateValue = new Animated.Value(0)
translate() {
this.translateValue.setValue(0)
Animated.timing(
this.translateValue,
{
toValue: 1,
duration: 14000,
easing: Easing.linear
}
).start(()=>this.translate())
}
const translateBackgroundImage1 = this.translateValue.interpolate({
inputRange: [0, 1],
outputRange: [0, -this.backgroundImageWidth]
})
const translateBackgroundImage2 = this.translateValue.interpolate({
inputRange: [0, 1],
outputRange: [this.backgroundImageWidth, -this.backgroundImageWidth]
})
return (
<View style={{flex:1}}>
<Animated.Image
style={{
flex: 1,
position: 'absolute',
left: translateBackgroundImage1,
}}
resizeMode={Image.resizeMode.cover}
source={this.backgroundImage}
/>
<Animated.Image
style={{
flex: 1,
position: 'absolute',
left: translateBackgroundImage2,
}}
resizeMode={Image.resizeMode.cover}
source={this.backgroundImage}
/>
To apply the same logic I used for setInterval() I would have translateBackgroundImage1 to start at x:0 in the first loop and then starts at x: ImageWidth
I'm not sure how to implement this with Animated
I eventually found a solution. It's not very clean but works.
I essentially have two Animated.image loaded from the same image. Then I have a translateValue1, which controls the left position of the first image. Then based on translateValue1, we have translateValue2 that has an offset of the imagewidth. translateValue2 controls the left position of the second image.
When the first image about to exit from the screen, it will go to the far right of the screen, and at the same time the second image will be moved to the front of the first image, so we need to change the offset to -imagewidth. Therefore there's a setState method in each of the two animation functions.
Inside the constructor I have these variables:
constructor(props) {
super(props);
this.backgroundImage = require('../assets/images/graidenttPastel.jpg');
this.backgroundImageWidth = resolveAssetSource(this.backgroundImage).width;
this.translateXValue1 = new Animated.Value(-1);
this.translateXValue2 = new Animated.Value(0);
this.animationLength = 20000;
this.state = {
translateXValue2Offset: this.backgroundImageWidth,
stopAnimation: false,
}
Then I have these two functions, each controls half of the loop:
translateXFirstHalfLoop() {
this.translateXValue1.setValue(-1);
this.setState({translateXValue2Offset: this.backgroundImageWidth});
this.firstHalfLoop = Animated.timing(
this.translateXValue1,
{
toValue: -this.backgroundImageWidth,
duration: this.animationLength/2,
easing: Easing.linear
}
).start(() => {
if(this.state.stopAnimation === false) {
this.translateXSecondHalfLoop()
}
})
}
translateXSecondHalfLoop() {
this.translateXValue1.setValue(this.backgroundImageWidth);
this.setState({translateXValue2Offset: -this.backgroundImageWidth});
this.secondHalfLoop = Animated.timing(
this.translateXValue1,
{
toValue: 0,
duration: this.animationLength/2,
easing: Easing.linear
}
).start(() => {
if(this.state.stopAnimation === false) {
this.translateXFirstHalfLoop()
}
})
}
Finally in the render() method, I have two Animated.Image like below:
render() {
this.translateXValue2 = Animated.add(this.translateXValue1, this.state.translateXValue2Offset);
return (
<SafeAreaView
style={[{backgroundColor: THEME_COLOR, flex: 1}]}
forceInset={{ bottom: 'never' }}>
<Animated.Image
style={{
position: 'absolute',
left: this.translateXValue1,
}}
resizestate={Image.resizeMode.cover}
source={this.backgroundImage}
/>
<Animated.Image
style={{
position: 'absolute',
left: this.translateXValue2,
}}
resizestate={Image.resizeMode.cover}
source={this.backgroundImage}
/>
<View style={{flex:1}}>
{this._renderScreenContent()}
</View>
</SafeAreaView>
);
}
Since each half loop function calls the other, we need to stop them before this component is unmounted, so we have this additional step below:
//clean up animation first
this.setState({stopAnimation: true}, () => {
this.props.navigation.goBack()
})
If you are looking to animate an ImageBackground, try
var AnimatedImage = Animated.createAnimatedComponent(ImageBackground)