Reputation: 2392
I have an animation consisting of a sequence of images: image01.png
, image02.png
, image03.png
, etc. How do I get these to animate continuously on React Native?
Upvotes: 10
Views: 7919
Reputation: 372
You can create functional component
import { useState, useEffect } from "react";
import { StyleSheet, Image } from "react-native";
const currentSourceImages = [
require('./image01.png'),
require('./image02.png'),
require('./image03.png')
];
const CurrentSourceIndicator = () => {
const [currentSourceIndex, setCurrentSourceIndex] = useState(0);
useEffect(() => {
const timeout = setTimeout(() => {
let index = currentSourceIndex + 1;
if (index >= currentSourceImages.length) {
index = 0;
}
setCurrentSourceIndex(index);
}, 1000);
return () => {
clearTimeout(timeout);
};
}, [currentSourceIndex]);
return (
<Image
source={currentSourceImages[currentSourceIndex]}
style={styles.currentSourceImage} />
);
}
const styles = StyleSheet.create({
currentSourceImage: {
width: 100,
height: 100,
resizeMode: 'contain'
},
});
export default CurrentSourceIndicator;
Upvotes: 1
Reputation: 1609
You can try with libraries:
First is more more efficient, second is in pure javascript. Another way is to implement it on your own way, like here: https://github.com/facebook/react-native/issues/9280
It should looks like this
export default class Animation extends Component {
constructor(props) {
super(props);
this.images = [
require('./img_01.png'),
require('./img_02.png'),
require('./img_03.png'),
];
this.next = this.next.bind(this);
this.state = {index: 0};
}
componentDidMount() {
this.next();
}
next() {
setTimeout(() => {
this.setState({index: (this.state.index+1)%3});
this.next();
}, 300);
}
render() {
return (
<Image
source={this.images[this.state.index]}
style={styles.image}
/>
)
}
}
Upvotes: 12