hackerl33t
hackerl33t

Reputation: 2365

Pass Animated.Value to styled component in react native?

How do I pass Animated.Value to styled components?

I'm getting this error whenever I uncomment bottom: ${p=>p.bottom}; line:

JSON value '[object Object]' of type NSString cannot be converted to a YGValue. Did you forget the % or pt suffix?

Here's my code:

  ...
  const [value] = useState(new Animated.Value(-100));

  return (
    <StyledView
      as={Animated.View}
      bottom={value}
      {...props}>
      <Button
        title={'Show'}
        onPress={() => {
          Animated.timing(value, {toValue: 0, duration: 300}).start();
        }}
      />
      <Button
        title={'Hide'}
        onPress={() => {
          Animated.timing(value, {toValue: -100, duration: 300}).start();
        }}
      />
    </StyledView>
  );
  ...

const StyledView = styled.View`
    position: absolute;
    height: 200;
    bottom: ${p=>p.bottom};
    background-color: yellow;
    width: 100%;
`;

Upvotes: 4

Views: 1331

Answers (1)

Thomas Ender
Thomas Ender

Reputation: 41

Don't pass Animated.Value to your styled-component but apply your Animated.Value as inline style to your styled Animated.View like so:

<AStyledAnimatedView style={{ opacity: yourAnimatedValue }} />

The reason is simply that styled components expects primitive types as we are dealing with CSS values here, but Animated.Value is of type Object.

Upvotes: 1

Related Questions