I would like when you press a button, the animation runs with the setState of btnLoaded that goes to true, for that's good but I would like that once the animation was done, when click on the buttons, the animation is not executed anymore because it has already been launched and finished.
I do not see how to do that.
Here is the function of animation:
startButtonAnimation = () => {
this.animatedValue.setValue(0);
if (this.state.btnLoaded) {
Animated.timing(
this.animatedValue,
{
toValue: 1,
duration: 500,
useNativeDriver: true,
easing: Easing.bezier(0.15, 0.73, 0.37, 1.2)
}
).start();
}}
And the code of button:
<TouchableOpacity
activeOpacity={0.9}
onPress={() => {
this.setState({
btnLoaded: true
});
setTimeout(() => this.startButtonAnimation(), 50);
}}>
Code in action :
Thank you for your help !
From the docs:
Animations are started by calling start() on your animation. start() takes a completion callback that will be called when the animation is done.
This:
startButtonAnimation = () => {
this.animatedValue.setValue(0);
if (!this.state.btnLoaded) {
this.setState({
btnLoaded: true,
});
Animated.timing(
this.animatedValue,
{
toValue: 1,
duration: 500,
useNativeDriver: true,
easing: Easing.bezier(0.15, 0.73, 0.37, 1.2)
}
).start(() => {
}};
...
<TouchableOpacity
activeOpacity={0.9}
onPress={() => {
setTimeout(() => this.startButtonAnimation(), 50);
}}
>
might do it. You should add more of your code to better understand what's going on.
By using this.animatedValue.setValue(0);, you restart the animation to 0. If you put this code outside of your button's callback, then the animation, even if restarted, will be already to its toValue (1 here), so it won't run again.
Related
I'm trying to test a gallery for the first time with Cypress but I'm having trouble trying to get the mouse events to work:
cy.get("img#front").should("be.visible");
cy.get("img#front")
.trigger("mousedown", { which: 1, pageX: 600, pageY: 100 })
.trigger("mousemove", { which: 1, pageX: -600, pageY: 100 })
.trigger("mouseup");
});
The image is visible on the page but when I do mouse down and mouse move on it nothing is happening. What I'm trying to do is press the mouse down and drag it left so the image changes to the next one in the gallery.
Using XY coordinates,
This is a simple example with the Cypress custom command, which I tried and it works for me,
* This reusable method is used to handle React drag and drop within cypress test.
*/
Cypress.Commands.add("dragAndDrop", (subject, target, dragIndex, dropIndex) => {
cy.get(subject).should("be.visible", { timeout: 2000 });
Cypress.log({
name: "DRAGNDROP",
message: `Dragging element ${subject} to ${target}`,
consoleProps: () => {
return {
subject: subject,
target: target
};
}
});
const BUTTON_INDEX = 0;
const SLOPPY_CLICK_THRESHOLD = 10;
cy.get(target).eq(dropIndex).then($target => {
let coordsDrop = $target[0].getBoundingClientRect();
cy.get(subject).eq(dragIndex).then(subject => {
const coordsDrag = subject[0].getBoundingClientRect();
cy.wrap(subject)
.trigger("mousedown", {
button: BUTTON_INDEX,
force: true
})
.trigger("mousemove", {
button: BUTTON_INDEX,
clientX: coordsDrag.x,
clientY: coordsDrag.y,
force: true
})
.wait(1000);
cy.get('body')
.trigger("mousemove", {
button: BUTTON_INDEX,
clientX: coordsDrop.x + SLOPPY_CLICK_THRESHOLD,
clientY: coordsDrop.y,
force: true
});
cy.get('body')
.trigger("mousemove", {
button: BUTTON_INDEX,
clientX: coordsDrop.x,
clientY: coordsDrop.y + SLOPPY_CLICK_THRESHOLD,
force: true
})
.wait(1000);
cy.get(target)
.trigger("mouseup");
});
});
});
in your cypress spec
cy.dragAndDrop(dragloc, droploc, 0, 0);
You can also try with a few changes
extracted from https://github.com/cypress-io/cypress/issues/3942
Click and drag within an image or canvas element has been the bane of my work-existence for a while. To be honest, I stumbled onto this post explicitly because I'm looking for something that will work in my current situation.
Do not be deterred, friend. I have a few examples that have worked for me in the past, hopefully this helps:
cy.get(".canvas-wrap > canvas")
.trigger("mousedown", 715, 155, {
button: 0,
force: true,
eventConstructor: "MouseEvent"
})
.trigger("mousemove", 100, 100, {
button: 0,
force: true,
eventConstructor: "MouseEvent"
})
.trigger("mouseup", 100, 100, {
button: 0,
force: true,
eventConstructor: "MouseEvent"
});
or
cy.get(".canvas-wrap")
.trigger("mousedown", 200, 200, { button: 0 })
.trigger("mousemove", { clientX: -250, clientY: -200 })
.trigger("mouseup", { force: true });
Anyway, I'd recommend experimenting with passing in button or event options, or just trying force: true and seeing if that gets you anywhere.
All the best
What is the best pattern, in react native, to animate components on state change?
For example I have a list of elements and tapping on one I want it to disappear and the ones below him to 'get up' filling the missing space
How can I make the transition smooth?
React-natives own animated API works really well.
Basically you have a value in state, which you connect with a style props, and change that value over time. (for examples follow link)
For smooth animations use usenativedriver (not always possible) and also, make sure you don't have debugger runnning in emulated/real device
EDIT: 2018-05-31
This is an example of how I've used it. Probably exist other ways of doing it
import { Animated, Text} from 'react-native';
class ShowCaseAnimation extends Component {
state = {
animations: {
height: new Animated.Value(0),
fade: new Animated.Value(0),
}
}
componentDidMount() {
const { height, fade } = this.state.animations;
if (this.props.animate) {
doneAnimation({ height, fade }).start(() => {
// Do stuff after animations
});
}
}
render() {
const { animations } = this.state;
return (
<Animated.View
style={{
height: animate? animations.height : 300,
opacity: animate? animations.fade: 1,
// other styling
}}
>
<Text> All your base are belong to us </Text>
</Animated.View>
);
}
}
*doneAnimation: *
import { Animated, Easing } from 'react-native';
export const doneAnimation = ({ height, fade }) => Animated.parallel([
Animated.timing(height, {
toValue: 300,
easing: Easing.elastic(),
duration: 500,
delay: 1500,
}),
Animated.timing(fade, {
toValue: 1,
easing: Easing.ease,
duration: 1000,
delay: 1500,
}),
]);
export default doneAnimation;
doneAnimation will change the state and perform the described animations.
This is how you can trigger an animation on state change in a functional component.
Say you have a Button that changes state with onPress:
<Button title="toggle" onPress={() => setValue(!Value)} />
then you can trigger the animation inside a useEffect with the Value
that changes in the dependency array:
const [Value, setValue] = useState(true);
useEffect(() => {
// Input your animation here
// ...
}, [Value]);
I'm using React Native Lottie Wrapper to show animation on screen.
I need a functionality to play/pause/resume animation.
Here is my a part of my code:
...
constructor(props) {
super(props);
this.state = {
progress: new Animated.Value(0)
};
}
static navigationOptions = {
title: "Details",
headerStyle: {
backgroundColor: '#f4511e',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
headerTruncatedBackTitle: 'List'
};
componentDidMount() {
this.animation.play();
}
playLottie() {
console.log('play');
}
pauseLottie() {
console.log('pause');
}
render() {
return (
<View>
<Animation
ref={animation => { this.animation = animation; }}
source={require('../../../../assets/anim/balloons.json')}
style={{height: 300, width: '100%'}}
loop={false}
progress={this.state.progress}
/>
<Text>Course with id: {this.props.navigation.state.params.courseId}</Text>
<Button
onPress={this.playLottie}
title="Play Lottie"
color="#841584"
accessibilityLabel="Play video"
/>
<Button
onPress={this.pauseLottie}
title="Pause Lottie"
color="#841584"
accessibilityLabel="Pause video"
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
...
The animation is playing well but I can't pause it and resume it.
Does anyone have a solution for this problem?
P.S. I have tried to use this.animation in pauseLottie() method but it said that is undefined.
Thank you in advance!
You can pause and play Lottie animation by changing the speed prop, where speed={0} puts LottieView component in pause and speed={1} plays it at normal speed.
Here is an example:
playAnimation = () => {
this.setState({speed: 1})
}
pauseAnimation = () => {
this.setState({speed: 0})
}
<LottieView
source={this.state.sourceAnimation}
speed={this.state.speed} />
You have to set the state from the play/pause functions. In order to access the state of the Component, you have to bind the function to the component class:
First option in your constructor:
constructor(props) {
super(props);
this.playLottie.bind(this);
this.pauseLottie.bind(this);
}
or second option when declaring inside class use the es6 function syntax:
playLottie = () => {
...
}
pauseLottie = () => {
...
}
Inside those function call setState and add the value you want to set it to. In your case I would:
playLottie = () => {
this.setState({ progress: true })
}
pauseLottie = () => {
this.setState({ progress: false })
}
It is important you bind those two functions to your class component, because you will not be able to access component props. Thats why it is throwing you an error setState is not a function
Your render looks good ;)
for me it didn't work well: we have to add setValue(0), then we need to improve pause/restart to maintain the playing speed and change easing function to avoid slow re-start. Let's also add looping:
constructor(props) {
super(props);
this.playLottie.bind(this);
this.pauseLottie.bind(this);
this.state = {
progress: new Animated.Value(0),
pausedProgress: 0
};
}
playLottie = () => {
Animated.timing(this.state.progress, {
toValue: 1,
duration: (10000 * (1 - this.state.pausedProgress)),
easing: Easing.linear,
}).start((value) => {
if (value.finished) this.restartAnimation();
});
}
restartAnimation = () => {
this.state.progress.setValue(0);
this.setState({ pausedProgress: 0 });
this.playAnimation();
}
pauseLottie = () => {
this.state.progress.stopAnimation(this.realProgress);
}
realProgress = (value) => {
console.log(value);
this.setState({ pausedProgress: value });
};
...
(Now) For me, it's working fine! Play and pause option work as expected.
If you use an Lottie animation that contains a loop you can control it all with the LottieView api built in. (if you are using a file that has the animation)
import Lottie from 'lottie-react-native'
const ref = useRef<AnimatedLottieView>()
const pause = () => {
ref.current.pause()
}
const resume = () => {
ref.current.resume()
}
const reset = () => {
ref.current.reset()
}
<Lottie
ref={ref}
source={source}
resizeMode={resizeMode}
loop={true}
duration={duration}
autoPlay={true}
onAnimationFinish={onFinish}
/>
react-native repeat animation
I searched how to implement a repeated animation ,and I found this.
//this.state.animatedStartValue = 0;
function cycleAnimation() {
Animated.sequence([
Animated.timing(this.state.animatedStartValue, {
toValue: 1,
duration: 500,
delay: 1000
}),
Animated.timing(this.state.animatedStartValue, {
toValue: 0,
duration: 500
})
]).start(event => {
if (event.finished) {
cycleAnimation();
}
});
}
It do works ,but when I use it in my project, I found that this solution will conflict with InteractionManager.runAfterInteractions, which is usually used to do something after animation.
I can use setTimeOut and so on to avoid this, but I want to ask ,is there any better solution to repeat animation , or to avoid this conflict?
use param {isInteraction: false }can avoid this problem.
//this.state.animatedStartValue = 0;
function cycleAnimation() {
Animated.sequence([
Animated.timing(this.state.animatedStartValue, {
toValue: 1,
duration: 500,
delay: 1000,
isInteraction: false,
}),
Animated.timing(this.state.animatedStartValue, {
toValue: 0,
duration: 500
})
]).start(event => {
if (event.finished) {
cycleAnimation();
}
});
}
React-native introduce new Animated API, I want to make a loop animation such as a bubble scale up then scale down and repeat that progress.
However I can not figure it out. I've tried write some code like below
class TestProject extends React.Component {
constructor(): void {
super();
this.state = {
bounceValue: new Animated.Value(0),
v: 1,
};
}
componentDidMount() {
this.state.bounceValue.setValue(1.5);
let animation = Animated.timing(this.state.bounceValue, {
toValue: this.state.v,
});
setInterval(() => {
animation.stop();
if (this.state.flag) {
this.state.v = 0.5;
this.state.bounceValue.setValue(0.5);
}
else {
this.state.v = 1.5;
this.state.bounceValue.setValue(1.5);
}
animation.start();
}, 5000);
}
render(): ReactElement {
return (
<View style={styles.imageContainer}>
<Image
style={styles.image}
source={{uri: 'http://image142-c.poco.cn/best_pocoers/20130517/91062013051716553599334223.jpg'}}
/>
<Animated.Text
style={[
styles.test,
{transform: [
{scale: this.state.bounceValue},
],}
]
}>
haha
</Animated.Text>
</View>
);
}
}
but not works very well.
Any suggestion will be appreciate.
There's now loop animation available:
Animated.loop(
Animated.sequence([
Animated.timing(this.state.animatedStartValue, {
toValue: 1,
duration: 500,
delay: 1000
}),
Animated.timing(this.state.animatedStartValue, {
toValue: 0,
duration: 500
})
]),
{
iterations: 4
}
).start()
I use the sequence method to pass an array of animations to cycle and then repeat the function.
//this.state.animatedStartValue = 0;
function cycleAnimation() {
Animated.sequence([
Animated.timing(this.state.animatedStartValue, {
toValue: 1,
duration: 500,
delay: 1000
}),
Animated.timing(this.state.animatedStartValue, {
toValue: 0,
duration: 500
})
]).start(() => {
cycleAnimation();
});
}
If I'm toggling that animation on it's own it will fade in/out, however I layer it on top of a base to mimic an active state or hotspot-style button
<TouchableOpacity>
<Animated.Image
source={activeImageSource}
style={this.state.animatedStartValue}}
/>
<Image source={nonActiveImageSource}
/>
</TouchableOpacity>
React Native Sequence Documentation
improved version of #bcomerford answer
//this.state.animatedStartValue = 0;
function cycleAnimation() {
Animated.sequence([
Animated.timing(this.state.animatedStartValue, {
toValue: 1,
duration: 500,
delay: 1000
}),
Animated.timing(this.state.animatedStartValue, {
toValue: 0,
duration: 500
})
]).start(event => {
if (event.finished) {
cycleAnimation();
}
});
}
Try something like this:
componentDidMount() {
this.bootAnimation();
}
bootAnimation() {
this.animation = Animated.loop(
Animated.timing(this.state.progress, {
toValue: 1,
duration: 5000
})
).start();
}
It seems that 'looping' is not supported by the Animated api for now.
I managed to do that by start the animation again when it finished.
startAnimation() {
Animated.timing(this._animatedValue, {
toValue: 100,
duration: 1000,
}).start(() => {
this.startAnimation();
});
}
Looking forward to a better solution...
You can set another animation then call the animation again:
An example I did to fade text in and out:
textAnimate: function() {
Animated.timing(
this.state.textOpacity,
{
toValue: 0.3,
duration: 500,
}
).start(() => {
Animated.timing(
this.state.textOpacity,
{
toValue: 1,
duration: 500,
}
).start(() => {
this.textAnimate();
});
});
},
componentDidMount: function() {
this.state.textOpacity.setValue(1)
this.textAnimate();
},
Not sure if it's hacky, but I use this:
Animated.spring(this.state.rotation, {
toValue: 5,
stiffness: 220, // the higher value, the faster the animation
damping: 0.000001, // never stop wiggle wiggle wiggle
}).start();
It's creating spring animation that will never (technically, for a very very very long time) stop waving.
For most of my cases it was enough. Also it has great performance as it does not require any JS tread action ever during animation.
If eventually you'd like to stop it gracefully:
Animated.spring(this.state.rotation, {
toValue: 0,
stiffness: 220, // the higher value, the faster the animation
damping: 10, // never stop wiggle wiggle wiggle
}).start();
And it'll nicely 'slow down' until it stops.
Here's another example for an infinite animation using hooks and iterations set to "infinity". Avoids the use of the recursion in previous answers which sometimes led to funky behaviour during e2e testing for us.
const rotation = React.useRef(new Animated.Value(0)).current;
function runAnimation() {
return Animated.loop(
Animated.timing(rotation, {
toValue: 1,
duration: 1200,
easing: Easing.linear,
useNativeDriver: true,
}),
{resetBeforeIteration: true, iterations: Number.MAX_SAFE_INTEGER},
);
}
React.useEffect(() => {
const animation = runAnimation();
return () => animation.stop();
}, []);