Search code examples
reactjsreact-nativeglamorous

How to use Animated values in Glamorous Component


I’m using Animated for web and I’m wondering is it possible to use Animated Values in a Glamorous component?

Like:

const AnimatedImageContainer = glamorous(Animated.div)(({ translateY }) => ({
  transform: `translateY(${translateY._value}px)`,
}));

<AnimatedImageContainer
  translateY={this.state.anim.interpolate({
    inputRange: [-200, 100],
    outputRange: [200, 0],
    extrapolate: 'clamp',
  })}
>
  <AnimatedImage src={image} />
</AnimatedImageContainer>

Or like:

<AnimatedImageContainer
  css={{
    transform: [
      {
        translateY: this.state.anim.interpolate({
          inputRange: [-200, 100],
          outputRange: [200, 0],
          extrapolate: 'clamp',
        }),
      },
    ],
  }}
>
  <AnimatedImage src={image} />
</AnimatedImageContainer>

Solution

  • Similar to React Native you can wrap your component in createAnimatedComponent().

    Something like this (https://codesandbox.io/s/93202y1qyo):

    import React from "react";
    import { render } from "react-dom";
    import glamorous from "glamorous";
    import Animated from "animated";
    
    const View = glamorous.div({
        display: "flex"
    });
    
    const Button = Animated.createAnimatedComponent(
        glamorous.button({
            position: "absolute",
            fontSize: 16,
            border: "none",
            display: "inline-block",
            padding: "10px 20px",
            textAlign: "center",
            borderRadius: 4,
            color: "#fff",
            boxShadow: "0 4px 6px rgba(50,50,93,.11), 0 1px 3px rgba(0,0,0,.08)",
            backgroundColor: "red"
        })
    );
    
    class App extends React.Component {
        state = {
            animation: new Animated.Value(0)
        };
    
        componentDidMount() {
            const { animation } = this.state;
    
            Animated.timing(animation, { toValue: 1, duration: 3000 }).start();
        }
    
        render() {
            const { animation } = this.state;
    
            return (
                <View>
                    <Button
                        style={{
                            opacity: animation
                        }}
                    >
                        Fade in...
                    </Button>
                </View>
            );
        }
    }
    
    render(<App />, document.getElementById("root"));