Lottie file animation play when selected (Expo) - javascript

I want it to play only when the card is selected, if the card is not selected it simply displays the lottie file but nothing is being played. Right now I get an error of cannot read property 'play' of null. When I remove the animationPress() and get the file to run it also start at the mentioned initialSegment that I'm passing into it.
What am I doing wrong here?
My card that the Lottie file is in:
const animation = useRef(null);
const animationPress = () => {
animation.current.play();
}
return(
{filteredData.map((item, index) => {
return (
<>
<TouchableOpacity onPress={() => setSelected(item), animationPress()}>
<View style={[{ alignItems: 'center' }, selected.id == item.id ? { paddingTop: 10 } : { paddingTop: 20 }]}>
<CardioCard style={selected.id == item.id ? { backgroundColor: 'green', fontFamily: 'ssb_SemiBold' } : {}} >
<CardItem style={[styles.card, selected.id == item.id ? { backgroundColor: 'green' } : {}]}>
<Text>
< LottieView
ref={animation}
source={require('../../assets/images/heartbeat.json')}
initialSegment={68,135}
autoPlay={true}
loop={true}
style={{ width: 100, height: 100 }} />
</Text>
</CardItem>
</CardioCard>
<Text style={[{ fontSize: 18, color: 'hsl(98, 0%, 11%)', paddingLeft: 15 }, selected.id == item.id ? { fontFamily: 'ssb_SemiBold' } : {}]}>{item.name}</Text>
</View>
</TouchableOpacity>
</>
)
})}
...
)
Edit
I also tried to do useState for the autoplay and loop button so they would be false but when the button is pressed it would turn true but the animation wouldn't load even after the button press.
const [playAnimation, setPlayAnimation] = useState(false);
<TouchableOpacity onPress={() => setPlayAnimation(true)}>
<LottieView
source={require('../../assets/images/heartbeat.json')}
autoPlay={playAnimation}
loop={playAnimation}
style={{ width: 100, height: 100 }}
/>
</TouchableOpacity>
this is driving me nuts and idk what to do anymore.

I'm new to react-native but I guess it's like react. Not sure to correctly understand the issue.
In this case, shouldn't you use animation.current instead of animation as your lottieView ref? or at least ensure that your ref animation is defined (not null) so that the container can be mounted even if not launched, this is also for your animationPress function. Also you should disable the autoPlay I guess (since you want to trigger the animation with a button).
< LottieView
ref={animation.current}
source={require('../../assets/images/heartbeat.json')}
initialSegment={68,135}
autoPlay={false}
loop={true}
style={{ width: 100, height: 100 }} />
or
{animation && < LottieView
ref={animation}
source={require('../../assets/images/heartbeat.json')}
initialSegment={68,135}
autoPlay={false}
loop={true}
style={{ width: 100, height: 100 }} />}
And of course
const animationPress = () => {
if(animation?.current) {
animation.current.play();
}
}

Related

React Native - How to set blurRadius onto a selected image

My app displays images and other info getting data from a JSON, and I want to set a blurRadius on the selected image when the unblur function is called.
My code is the following:
const [blur, setBlur] = useState(160);
const unblur = () => {
if(blur == 160){
setBlur(0);
}
}
{isLoading ? <ActivityIndicator/> : (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<>
<Text style={{ textAlign: "left", color: 'white', fontSize: 24 }}>
<Image style={{ alignSelf: "center" }} source={{uri: item.profile_picture, width: 48, height: 48}} />
{item.username}
</Text>
<TouchableOpacity onPress={() => unblur()}>
<Image style={{ alignSelf: "center" }} blurRadius={blur} source={{uri: item.picture, width: 400, height: 320}} />
</TouchableOpacity>
<Text style={{ textAlign: "left", color: 'white', fontSize: 24 }}>
ID {item.id}
</Text>
<Text>
{'\n'}{'\n'}
</Text>
</>
)}
/>
)}
I want to change the {blur} value for a given image when I tap the TouchableOpacity component of the image I want to unblur. Right in this moment when I tap an image, all the images in the list are getting unblurred.
You should add the blur values inside your items like this. Create a new components called Items. Then, add the blur state inside it. (not inside Main).
const Main = () => {
if (isLoading) {
return;
<ActivityIndicator />;
}
return (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => <Item item={item} />}
/>
);
};
const Item = ({ item }) => {
const [blur, setBlur] = useState(160);
const unblur = () => {
if (blur == 160) {
setBlur(0);
}
};
return (
<>
<Text style={{ textAlign: "left", color: "white", fontSize: 24 }}>
<Image
style={{ alignSelf: "center" }}
source={{ uri: item.profile_picture, width: 48, height: 48 }}
/>
{item.username}
</Text>
<TouchableOpacity onPress={() => unblur()}>
<Image
style={{ alignSelf: "center" }}
blurRadius={blur}
source={{ uri: item.picture, width: 400, height: 320 }}
/>
</TouchableOpacity>
<Text style={{ textAlign: "left", color: "white", fontSize: 24 }}>
ID {item.id}
</Text>
<Text>
{"\n"}
{"\n"}
</Text>
</>
);
};
Also, may I suggest you can use 'onPressIn'. That way, image will unblur when the finger tap the image, not press the image. But that was your decision.

How to stop Array from constantly re-rendering

I have an image array where I am updating each value when I click on a button in react and pick an image. However the array is constantly rerendering when I only want it to when I pick an image.
Here is my code:
function OnboardingUploadPhotos() {
const [modalVisible, setModalVisible] = useState(false);
const [permissionStatus, setPermissionStatus] = useState('');
const [files, setFiles] = useState<string[]>([]);
const [fileArray, setFileArray] = useState<string[]>(['', '', '', '', '', '', '']);
const setPermissions = useCallback(val => {
setPermissionStatus(val);
}, [setPermissionStatus]);
const setIsModalVisible = useCallback(val => {
setModalVisible(val);
}, [setModalVisible]);
async function fetchAssets() {
const recentCameraRoll = await MediaLibrary.getAssetsAsync({first: 11});
setFiles(recentCameraRoll.assets.slice(1).map(file => file.uri));
}
function replaceFileState(file: string, index: number) {
let f = [...fileArray];
f[index] = file;
setFileArray(f);
}
useEffect(() => {
fetchAssets();
}, [fetchAssets]);
return (
<View>
{permissionStatus ?
<Modal style={styles.bottomModalView} isVisible={modalVisible} backdropOpacity={0}
onBackdropPress={() => setModalVisible(false)}>
<View style={styles.modal}>
<TouchableOpacity>
<Text style={{
borderBottomWidth: 1,
borderBottomColor: '#FFF',
color: '#FFF',
textDecorationLine: 'underline',
alignSelf: 'flex-end',
justifyContent: 'center',
paddingTop: 40
}}>All photos</Text>
</TouchableOpacity>
<ScrollView horizontal={true} scrollEnabled={true}
contentContainerStyle={{justifyContent: 'center', alignItems: 'center'}}>
{files.map((file, index) => {
return (
<TouchableWithoutFeedback key={index} onPress={() => replaceFileState(file, index)}>
<Image
key={file}
style={{width: 100, height: 100, marginLeft: 10, marginRight: 10, borderRadius: 4}}
source={{uri: file}}
/>
</TouchableWithoutFeedback>
);
})}
</ScrollView>
<Text style={{fontSize: 22, color: '#FFF', marginLeft: 20, marginBottom: 20}}>Your photos</Text>
</View>
</Modal> :
null
}
<Text>Upload your photos</Text>
<View style={{flexDirection: "row", flexWrap: "wrap", justifyContent: 'space-evenly'}}>
{fileArray.slice(0,6).map((image, index) => {
console.log(fileArray)
return (
image != '' ?
<Image
key={image}
style={{width: 100, height: 100, borderRadius: 100}}
source={{uri: image}}
/> :
<OnboardingPhoto key={index} setStatus={setPermissions} setModal={setIsModalVisible}/>
)
})}
</View>
</View>
);
}
It is a modal that has all the users latest images and on click of each image it replaces the empty placeholder image with the users image on the screen. However it constantly rerenders. Id say put it in a useEffect but I do not know where! Any help would be great, thanks!
I think you need to define a key property on the TouchableWithoutFeedback component.
See the guidelines here: https://reactjs.org/docs/lists-and-keys.html
Hooks are ment to be used inside Function Components, that's maybe one of the reasons.

How to play a specific video on a React native ScrollView carousel?

I have a scrollview that has as a child an array of video components. It displays on the UI a carousel of videos. I would like the user to be able to click a play button that is above the video and play that video, but the way my logic is set, all the videos play together because the condition to play the video lives in a react useState.
see the code:
const VideosView = (props) => {
const videoClips = props.route.params.data;
const [state, setState] = React.useState(0);
const [play, setPlay] = React.useState(false);
return (
<>
<SafeAreaView pointerEvents='box-none' style={styles.root}>
<Header
goBack={() => props.navigation.goBack()}
title={state === 0 ? 'RYGGRöRLIGHET' : 'STYRKA & BALANS'}
/>
<View style={styles.paragraphsContainer}>
<Text style={styles.title}>
{state === 0 ? 'Ryggrörlighet' : 'Styrka & Balans'}
</Text>
<Text style={styles.paragraph}>
'Utför övningen i ca 5 min för bästa resultat.'
</Text>
<View style={styles.circlesContainer}>
{renderImages.map((_, index) => {
return (
<TouchableOpacity key={index} onPress={() => setState(0)}>
<View
style={[
styles.circles,
{ opacity: index === state ? 1 : 0.5 }
]}
/>
</TouchableOpacity>
);
})}
</View>
</View>
</SafeAreaView>
<View style={styles.scrollViewContainer}>
<ScrollView
bounces={false}
showsHorizontalScrollIndicator={false}
scrollEventThrottle={30}
onScroll={({ nativeEvent }) => {
const slide = Math.ceil(
nativeEvent.contentOffset.x / nativeEvent.layoutMeasurement.width
);
if (slide !== state) {
setState(slide);
}
}}
horizontal>
{videoClips.map((video, index) => (
<View style={{ position: 'relative' }}>
{!play && (
<TouchableOpacity
style={{
position: 'absolute',
backgroundColor: 'rgba(255,255,255,0.5)',
alignSelf: 'center',
top: 130,
width: 160,
height: 160,
borderRadius: 500,
zIndex: 4000
}}
onPress={() => setPlay(true)}></TouchableOpacity>
)}
<Video
shouldPlay={play}
key={index}
source={{
uri: video
}}
resizeMode='cover'
style={{ width: wp('100%'), height: hp('100%') }}
/>
</View>
))}
</ScrollView>
</View>
</>
);
};
I would like the user to click a button and play one video, use the carousel to go to next video, click play and play the next video.
Please, help.
If you change the play state from Boolean to Number you will probably solve your problem. Here is how:
const [videoBeingDisplayedIndex, setVideoBeingDisplayedIndex] = React.useState(5);
const [play, setPlay] = React.useState(5); // If it is equals to the video id the video should play, else it should not
...
<Button onClick={() => setPlay(videoBeingDisplayedIndex)}>
Play Video
</Button>
<VideoCarousel>
{
myVideoList.map((video, index) => {
return (
<Video
content={video}
index={index}
play={play === index} // Check if the current play state is equals to the video unique id
/>
);
})
}
</VideoCarousel>
...
PS.: please, have in mind that this snippet is abstracting the react-native elements and focusing on the problem.

How to add Lottie animation in Alert in react native

on sumit buttoe event i am calling below fuction ,where i am opening one Alert and insid ethe alert I want opne LottieAnimation , like when I click on button first Alet will open with animation till the time response is coming , after getting the response I'll chnage animation ans close the Alert , normal alert is comign but with Animation nothin is coming . Please help. I have atteched image .
blockSimNumber = async () => {
{this.props.isWalletEnable &&
Alert.alert(
'
<View style={{ height: deviceHeight, width: deviceWidth }}>
<LottieView source={require('../animations/wallet.json')} autoPlay loop />
</View>
<View style={{ height: deviceHeight, width: deviceWidth }}>
<LottieView source={require('../animations/success_tick.json')} autoPlay loop />
</View>
Hang on !',
'We are creating your wallet for you',
[
{
text: 'Close',
onPress: () => console.log('Cancel Pressed'),
style: 'Cancel',
},
]
)
}
// <View style={{ height: deviceHeight, width: deviceWidth }}>
// <LottieView source={require('../animations/wallet.json')} autoPlay loop />
// </View>
await this.props.updatePhysicalResource(this.props.physicalResourceId);
}
Just use a modal instead of an Alert
Here's how to use a modal:
import { View, Modal } from 'react-native';
import LottieView from 'lottie-react-native'
[...]
constructor(props) {
super(props)
this.state = {
IsModalVisible: false
}
}
render(){
return(
<Modal
animationType="fade"
style={{flex: 1}}
transparent={true}
visible={this.state.IsModalVisible}
onRequestClose={() => this.setState({IsModalVisible: false})}
>
<View style={{backgroundColor: 'white', justifyContent: 'center', alignItems: 'center', height: '40%', width: '90%'}}>
<LottieView style={{height: '50%', width: '50%'}} source={require('../animations/success_tick.json')} autoPlay loop />
</View>
</Modal>
)
}
Then just change the IsModalVisible value to true when you want to (This is just a example)

Rendering Child Component in React Native

I am using React Native and React Navigation to build a simple app.
I have got the basic structure working with stub state but I am having problem with changing state via callback and re-render.
In my screen, I have simple start button
`<View style={styles.buttonContainer}>
<TouchableOpacity
style={[myStyles.buttonStyle, { backgroundColor: color }]}
onPress={() => handlePress(button.title)}
>
<Text style={myStyles.textStyle}>{button.title}</Text>
</TouchableOpacity>
</View>`
Problem:
After I update my parent Component state, my child component does not instantly render to match the state change. I understood React will re-render all child components when parent state is changed?
Instead, I have to move back to previous screen and navigate again to my button screen to see that the button's color and text has changed correctly.
I've read about requiring a componentWillReceiveProps(nextProps) handler but I am not sure how to use it. I put a console.log('nextProps', nextProps) inside but it does not get fired.
From navigation perspective, the Root component is on index[0] and my button view is at index[3] so it's the 3rd screen from the root.
EDIT 1: Added Code
myButton screen:
export class TeamsScreen extends React.Component {
static navigationOptions = ({ navigation }) => ({
title: `${navigation.state.params.game.name}: Select Team`,
headerTintColor: 'white',
headerStyle: {
backgroundColor: 'black',
},
headerVisible: true
})
componentWillReceiveProps(nextProps) {
console.log('nextProps', nextProps);
}
render() {
const { navigate, setParams } = this.props.navigation;
const { game, player, setGameState } = this.props.navigation.state.params;
const color = game.status === 'Start' ? 'green' : 'red';
const index = game.indexOf(player);
const status = game.status;
console.log('index', index);
console.log('status', status);
return (
<View style={styles.container}>
<View style={styles.buttonContainer}>
<TouchableOpacity
style={[myStyles.buttonStyle, { backgroundColor: color }]}
onPress={() => setGameState(index, status)}
>
<Text style={myStyles.textStyle}>{game.status}</Text>
</TouchableOpacity>
</View>
<View style={styles.buttonContainer}>
<Button
onPress={() => navigate('ChangeDriverScreen', { team, game })}
title='Change Driver'
/>
</View>
<View style={{ marginTop: 40, marginBottom: 20 }}>
<Text style={{ fontSize: 16, color: 'white', alignSelf: 'center' }}>Teams</Text>
</View>
<View style={{ height: 250 }}>
<FlatList
data={player.teams}
renderItem={({item}) =>
<View style={styles.buttonContainer}>
<Button
onPress={() => navigate('TeamSelectedStartScreen', { team: item })}
title={item.name}
/>
</View>}
keyExtractor={item => item.name}
/>
</View>
<Image
style={{ alignSelf: 'center', justifyContent: 'flex-end', height: 75, width: 250, resizeMode: 'stretch'}}
source={require('./images/icons/playerPlaceholder.png')}
/>
</View>
)}}
Then the onPress function that is called back:
setGameState = (gameIndex, status) => {
console.log('setGameState', gameIndex, status);
console.log('gameStateBefore', this.state.game);
const newGameState = this.state.game.map(t => {
console.log(this.state.game.indexOf(t));
if (this.state.game.indexOf(t) === gameIndex) {
const newStatus = status === 'Start' ? 'Stop' : 'Start';
t.status = newStatus; /*eslint no-param-reassign: "off"*/
console.log('inside if', t.status);
console.log('inside if game', t);
return t;
}
return t;
});
console.log('new Game State', newGameState);
this.setState(() => ({
game: newGameState
}));
}
So the setState method works (as re-navigating back to screen 3 shows the correct state but core question is how to get immediate re-render of screen 3 when setState is called from Screen 0.

Categories