Skip to content

Instantly share code, notes, and snippets.

@MichaelDanielTom
Created May 20, 2016 03:40
Show Gist options
  • Save MichaelDanielTom/252f8807b4d8d89049d4244157d470fc to your computer and use it in GitHub Desktop.
Save MichaelDanielTom/252f8807b4d8d89049d4244157d470fc to your computer and use it in GitHub Desktop.
/**
* HighlightableImage.js
*
* If we simply change the source prop of an Image in the render method, the
* image blinks, and there is no image for a fraction of a second. This is
* solved by mounting 2 images and changing their opacity.
*
*/
import React from 'react'
import {
Image,
StyleSheet,
Text,
TouchableNativeFeedback,
View
} from 'react-native'
import flattenStyle from 'flattenStyle'
export default class HighlightableImage extends React.Component {
static propTypes = {
highlightSource: React.PropTypes.number, // This is what is returned by a 'require()'
noHighlightSource: React.PropTypes.number,
style: View.propTypes.style,
highlighted: React.PropTypes.bool
}
static defaultProps = {
style: {},
highlighted: false
}
render() {
let style = flattenStyle(this.props.style)
// Must explicitly set dimensions for image to resize properly
let imageStyle = [styles.image, {
width: style.width,
height: style.height
}]
return (
<View style={[styles.imageContainer, this.props.style]}>
<Image
source={this.props.highlightSource}
style={[...imageStyle, {opacity: this.props.highlighted ? 1 : 0}]}
/>
<Image
source={this.props.noHighlightSource}
style={[...imageStyle, {opacity: this.props.highlighted ? 0 : 1}]}
/>
</View>
)
}
}
const styles = StyleSheet.create({
image: {
position: 'absolute',
left: 0,
top: 0,
resizeMode: 'contain',
},
})
@quantumproducer
Copy link

flatten-style is now unpublished

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