Chris Rice
Chris Rice

Reputation: 819

Updating state during animation stops animation from functioning

I'm attempting to use a draggable component that when dragged also creates a progress bar like effect. It's almost working but I have something weird going on.

In my onDrag handler I update the state of the bar so that the bar can render its appropriate width. But as soon as I set the state, my animation resets because the internal panResponder re-creates itself.

I'm new to react (and react-native). There are several similar problems but i can't work out what they are doing to resolve the problem.

React Native state update during animation "resets" the animation

Update state during animation in react native?

Here is a snack of the component I'm trying to produce.

https://snack.expo.io/mHaw0gLLz

Upvotes: 1

Views: 1417

Answers (1)

Yoel
Yoel

Reputation: 7985

When you change the state he renders everything again and gives you the position of X again according to the figure you gave him

You can use the Animated component to change the drag width without changing the state

Attaches you an example

Successfully :)

add import

import React, { useState, useRef } from 'react';
import { Text, View, StyleSheet, Animated } from 'react-native';

add ref animated value

const widthAnim = useRef(new Animated.Value(0)).current;

change animated value

const onDrag=(event, gestureState)=> {
  let width = Math.min(Math.max(gestureState.moveX, iconSize), dragWidth);
  Animated.timing(widthAnim, {
    toValue: Math.max(width - padding, 0),
    duration: 1,
  }).start();
}

Now use it in bar component!

<Animated.View style={[styles.bar, { width: widthAnim }]} />

fix expo

Upvotes: 1

Related Questions