Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@jordanmkoncz jordanmkoncz commented Feb 6, 2017

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

This comment has been minimized.

Copy link

@canhnht canhnht commented Aug 2, 2017

👍

@Tim152

This comment has been minimized.

Copy link

@Tim152 Tim152 commented Oct 17, 2017

Thank you!

@amitava82

This comment has been minimized.

Copy link

@amitava82 amitava82 commented Oct 20, 2017

👍

@carlos-arteaga

This comment has been minimized.

Copy link

@carlos-arteaga carlos-arteaga commented Sep 14, 2018

👍

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