Skip to content

Instantly share code, notes, and snippets.

@loganpowell
Created January 15, 2018 21:00
Show Gist options
  • Save loganpowell/2be75c1d0266d301fb1446ed14ebe7e6 to your computer and use it in GitHub Desktop.
Save loganpowell/2be75c1d0266d301fb1446ed14ebe7e6 to your computer and use it in GitHub Desktop.
Styled-Components with Animated.js (for React Native, but...)

React Native

styled-components has a ReactNative mode that works exactly the same, except you import the things from styled-components/native:

import styled from 'styled-components/native';

const StyledView = styled.View`
  background-color: papayawhip;
`;

const StyledText = styled.Text`
  color: palevioletred;
`;

class MyReactNativeComponent extends React.Component {
  render() {
    return (
      <StyledView>
        <StyledText>Hello World!</StyledText>
      </StyledView>
    )
  }
}

We also support more complex styles (like transform), which would normally be an array, and shorthands (e.g. for margin) thanks to css-to-react-native! Imagine how you'd write the property in ReactNative, guess how you'd transfer it to CSS and you're probably right:

const RotatedBox = styled.View`
  transform: rotate(90deg);
  text-shadow-offset: 10 5;
  font-variant: small-caps;
  margin: 5 7 2;
`

You cannot use the keyframes and injectGlobal helpers since ReactNative doesn't support keyframes or global styles. We will also log a warning if you use media queries or nesting in your CSS.

Animations

To get React Native animations working, create a styled component, passing the animatable component as an argument (e.g: styled(Animated.View) instead of styled.View.) Define all your non-changing styles in the usual way, then pass your Animated.Values in as style props.

import styled from 'styled-components/native'
// Make sure to import Animated from react-native.
import {Animated} from 'react-native'

// Pass your animatable component as styled's argument here.
const BaseStyles = styled(Animated.View)`
  height: 100;
  width: 100;
  background-color: red;
`

class AnimateOpacity extends Component {
  constructor() {
    super()

    this.state = {
      opacity: new Animated.Value(0)
    }
  }

  componentWillMount() {
    Animated.timing(this.state.opacity, {
      toValue: 1,
      duration: 1000,
    }).start()
  }

  render() {
    const { opacity } = this.state;
    // Pass in your animated values here!
    return <BaseStyles style={{ opacity }} />
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment