Home > OS >  Reanimated: animated view doesn't react to value changes
Reanimated: animated view doesn't react to value changes

Time:10-18

What you will see below is a minimised version of a bigger draggable solution I'm trying to implement—and it requires to have an animated view that would react to changes in animated style. This example isn't containing any gesture code since it's irrelevant here.

I have two rectangles: first is a Button that changes offset value randomly; second one is AnimatedRectangle that is supposed to be changing position each time the Button is pressed. That's it.

Expected result: AnimatedRectangle moving when Button is pressed. Actual result: nothing moves.

FYI: share values, as well as animated style are changing, but the animated view doesn't seem to react to these changes.

Weird part is that when I was trying the same code in another project it worked in some files but not in others, although the styling and the way these different components were defined are the same. I have no idea why it happens.

Steps to reproduce:

  1. Click on the Button
  2. Observe the blue rectangle

Repo link: https://github.com/tumanov-alex/reanimated-not-working

import React from 'react';
import {View, TouchableOpacity, Animated, Text} from 'react-native';

import {useAnimatedStyle, useSharedValue} from 'react-native-reanimated';

const App = () => {
  const offset = useSharedValue({x: 0, y: 0});
  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{translateX: offset.value.x}, {translateY: offset.value.y}],
  }));

  const Button = () => (
    <TouchableOpacity
      onPress={() => {
        offset.value = {
          x: Math.random() * 100,
          y: Math.random() * 100,
        };
      }}>
      <View style={{width: 500, height: 500, backgroundColor: 'grey'}} />
    </TouchableOpacity>
  );
  const AnimatedRectangle = () => (
    <Animated.View
      style={[
        animatedStyle,
        {
          width: 100,
          height: 100,
          backgroundColor: 'blue',
        },
      ]}>
      <Text style={{color: 'white'}}>Why I'm not moving?</Text>
    </Animated.View>
  );

  return (
    <View style={{flex: 1}}>
      <Button />
      <AnimatedRectangle />
    </View>
  );
};

export default App;

Reanimated version: 2.11.0

React Native version: 0.70.3

Platforms: Android, iOS

Device: iOS simulator

CodePudding user response:

I think that you have to import Animated directly from react-native-reanimated library and not from react-native:

Like this.

import Animated, {useAnimatedStyle, useSharedValue} from 'react-native-reanimated';
  • Related