Skip to content

Instantly share code, notes, and snippets.

@sharathprabhal
Created February 11, 2016 11:41
Show Gist options
  • Save sharathprabhal/a54565ee1ce42d332f09 to your computer and use it in GitHub Desktop.
Save sharathprabhal/a54565ee1ce42d332f09 to your computer and use it in GitHub Desktop.
import React from 'react-native'
var {
Image,
Animated,
View
} = React
module.exports = React.createClass({
getInitialState() {
return {
opacity: new Animated.Value(0)
}
},
onLoad() {
Animated.timing(this.state.opacity, {
toValue: 1,
duration: 250
}).start()
},
render() {
return (
<View
width={this.props.style.width}
height={this.props.style.height}
backgroundColor={'#CCC'}
>
<Animated.Image
resizeMode={'contain'}
key={this.props.key}
style={[{opacity: this.state.opacity}, this.props.style]}
source={this.props.source}
onLoad={this.onLoad} />
</View>
)
}
});
@jordanmkoncz
Copy link

Thanks for this @sharathprabhal.

I tweaked this code slightly when using it in my project to allow for easier use:

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

class FadeInImage extends Component {
  static propTypes = {
    source: React.PropTypes.object.isRequired,
    backgroundColor: React.PropTypes.string.isRequired,
    resizeMode: React.PropTypes.string.isRequired,
    style: React.PropTypes.any,
  };

  static defaultProps = {
    backgroundColor: '#ccc',
    resizeMode: 'cover',
    style: {},
  };

  constructor() {
    super();

    this.onLoad = this.onLoad.bind(this);

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

  onLoad() {
    Animated.timing(this.state.opacity, {
      toValue: 1,
      duration: 250,
    }).start();
  }

  render() {
    const style = [this.props.style, { opacity: this.state.opacity }];

    return (
      <View
        style={{ flex: 1 }}
        backgroundColor={this.props.backgroundColor}
      >
        <Animated.Image
          style={style}
          resizeMode={this.props.resizeMode}
          source={this.props.source}
          onLoad={this.onLoad}
        />
      </View>
    );
  }
}

export default FadeInImage;

@canhnht
Copy link

canhnht commented Aug 2, 2017

👍

@cheesytim
Copy link

Thank you!

@amitava82
Copy link

👍

@carlos-arteaga
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment