Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6208

react-native-renimated animation reseting on value set

$
0
0

What am I trying to do?

I am trying to animate a header from my app using react-native-reanimated.

What I did until now?

I've already coded the animation, however the animation reset when I try to animate back to it original value.

Code

import React, { useContext } from 'react';
import Reanimated, { Easing, Extrapolate } from 'react-native-reanimated';
import PacientCategoryButton from '../PacientCategoryButton';
import PacientCategoryIndexContext from './contex';
import { Container } from './styles';

const {
  Value,
  Clock,
  createAnimatedComponent,
  interpolate,
  block,
  cond,
  clockRunning,
  set,
  startClock,
  stopClock,
  useCode,
  timing,
  onChange
} = Reanimated;

const AnimatedContainer = createAnimatedComponent(Container);

export interface PacientCategorySelectorProps {
  setIndex: React.Dispatch<React.SetStateAction<number>>;
}

function runTiming(
  clock: Reanimated.Clock,
  value: Reanimated.Value<number>,
  config: Reanimated.TimingConfig
) {
  const state = {
    finished: new Value(0),
    position: new Value(0),
    time: new Value(0),
    frameTime: new Value(0)
  };

  return block([
    onChange(config.toValue, set(state.frameTime, 0)),
    cond(clockRunning(clock), 0, [
      set(state.finished, 0),
      set(state.time, 0),
      set(state.position, value),
      set(state.frameTime, 0),
      startClock(clock)
    ]),
    timing(clock, state, config),
    cond(state.finished, stopClock(clock)),
    state.position
  ]);
}

const PacientCategorySelector = ({
  setIndex
}: PacientCategorySelectorProps) => {
  const currentIndex = useContext(PacientCategoryIndexContext);
  const animation = new Value<number>(0);
  const translateX = interpolate(animation, {
    inputRange: [0, 1],
    outputRange: [64, -64],
    extrapolate: Extrapolate.EXTEND
  });

  useCode(
    () => [
      set(
        animation,
        runTiming(new Clock(), animation, {
          duration: 270,
          easing: Easing.inOut(Easing.ease),
          toValue: currentIndex
        })
      )
    ],
    [currentIndex]
  );

  return (
    <AnimatedContainer style={{ transform: [{ translateX }] }}>
      <PacientCategoryButton index={0} setIndex={setIndex} label="Hoje" />
      <PacientCategoryButton index={1} setIndex={setIndex} label="Todos" />
    </AnimatedContainer>
  );
};

export default PacientCategorySelector;

Result

https://youtu.be/sT96_lp_WqM


Viewing all articles
Browse latest Browse all 6208

Trending Articles