Using Animated with styled-components (react-native)

11.8k views Asked by At

I'm experiencing an error stating following (tested via iOS):

Cannot read property 'getScrollableNode' of null

While trying to use react-native's Animated along side styled-components styling tool for react and react-native.

Here is example of a <Logo /> component I created:

import React from 'react';
import { Image, Dimensions } from 'react-native';
import styled from 'styled-components/native';

const { width } = Dimensions.get('window');
const logoWidth = width - (width * 0.2);
const logoHeight = logoWidth * 0.4516;

const SLogoImage = styled(Image)`
  width: ${logoWidth};
  height: ${logoHeight};
`;

const Logo = ({ ...rest }) => (
  <SLogoImage
    source={require('../assets/logo.png')}
    {...rest}
  />
);

export default Logo;

I am then importing this component into one of my scenes where I want to apply animation to it:

import React from 'react';
import { View, Animated } from 'react-native';
import Logo from '../components/Logo';

const ALogo = Animated.createAnimatedComponent(Logo);

class HomeScene extends Component {
  state = {
    fadeAnim: new Animated.Value(0)
  }

  componentDidMount() {
    Animated.timing(
      this.state.fadeAnim,
      { toValue: 1 }
    ).start()
  }

  render() {
    <View>
      <ALogo style={{ opacity: this.state.fadeAnim }} />
    </View>

  }
}

export default HomeScene;

And this results in error mentioned above, tried Googling it and wasn't able to find any sort of explanation to what it is. feel free to request further details if necessary.

Related GitHub issue: https://github.com/styled-components/styled-components/issues/341

1

There are 1 answers

1
Abdellah Stands with Gaza On BEST ANSWER

This issue is actually not related to styled-components. Rather, it's a react-native one

The workaround for this is to use class instead of a stateless component.

class Logo extends React.Component {
  render () {
    return (
      <SLogoImage
        source={require('./geofence.gif')}
        {...this.props}
      />
    )
  }
}

Here is a github repo where it is working. If anyone wants to reproduce it, Just uncomment 14-21 lines to see the error.

I think the issue comes from Animated trying to attach ref to a stateless component. And stateless components cannot have refs.