Created
January 8, 2018 15:29
-
-
Save infostreams/1a848878ba82fdc9ac92e4d61b957c6f to your computer and use it in GitHub Desktop.
Use "react-native-img-cache" with multiple source images
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react" | |
import PropTypes from "prop-types" | |
import {CachedImage} from "react-native-img-cache" | |
class CachedImageMultiSource extends React.Component { | |
static propTypes = { | |
...CachedImage.propTypes, | |
source: PropTypes.arrayOf(PropTypes.object), | |
width: PropTypes.number.isRequired, | |
height: PropTypes.number.isRequired, | |
acceptable: PropTypes.number | |
}; | |
static defaultProps = { | |
acceptable: 0.90, | |
width: 0, | |
height: 0 | |
}; | |
findBestImage() { | |
if (Object.prototype.toString.call(this.props.source) !== "[object Array]") { | |
// source is NOT an array with multiple sizes | |
return this.props.source; | |
} | |
if (!this.props.width || !this.props.height) { | |
// we don't know width or height, so just return first image | |
return this.props.source[0]; | |
} | |
let sizes = this.props.source.slice().sort((a, b) => { | |
if (a.height > b.height) { | |
return 1 | |
} else if (b.height > a.height) { | |
return -1 | |
} | |
return 0 | |
}) | |
const acceptable = this.props.acceptable; | |
let winner = sizes.find((size) => { | |
if (size.width >= (this.props.width * acceptable) && | |
size.height >= (this.props.height * acceptable)) { | |
return size | |
} | |
}); | |
return winner || sizes[0]; | |
} | |
render() { | |
return ( | |
<CachedImage | |
{...this.props} | |
source={this.findBestImage()} | |
/> | |
) | |
} | |
} | |
export default CachedImageMultiSource |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment