The proposed solution works, but you have to download image twice, once to determine the size and another to actually show the image, this is a different approach, image is loaded squared initially and resized.
import React, { Component, } from "react";
import { Image } from "react-native";
import PropTypes from 'prop-types'
export default class ScaledImage extends Component {
state = {}
componentWillMount() {
const { uri, width, height } = this.props;
this.setState({ source: { uri }, width: width || height, height: height || width });
}
render() {
return (
<Image
source={this.state.source}
onLoad={(value) => {
const { height, width } = value.nativeEvent.source;
if (this.props.width && !this.props.height) {
this.setState({
width: this.props.width,
height: height * (this.props.width / width)
});
} else if (!this.props.width && this.props.height) {
this.setState({
width: width * (this.props.height / height),
height: this.props.height
});
} else {
this.setState({ width: width, height: height });
}
}}
style={{ height: this.state.height, width: this.state.width }}
/>
);
}
}
ScaledImage.propTypes = {
uri: PropTypes.string.isRequired,
width: PropTypes.number,
height: PropTypes.number
};
If you are writing React-Native class with ES6, following format will be followed. It includes life cycle methods of RN for the class making network calls.
<!-- language: lang-js -->
import React, {Component} from 'react';
import {
AppRegistry, StyleSheet, View, Text, Image
ToastAndroid
} from 'react-native';
import * as Progress from 'react-native-progress';
export default class RNClass extends Component{
constructor(props){
super(props);
this.state= {
uri: this.props.uri,
loading:false
}
}
renderLoadingView(){
return(
<View style={{justifyContent:'center',alignItems:'center',flex:1}}>
<Progress.Circle size={30} indeterminate={true} />
<Text>
Loading Data...
</Text>
</View>
);
}
renderLoadedView(){
return(
<View>
</View>
);
}
fetchData(){
fetch(this.state.uri)
.then((response) => response.json())
.then((result)=>{
})
.done();
this.setState({
loading:true
});
this.renderLoadedView();
}
componentDidMount(){
this.fetchData();
}
render(){
if(!this.state.loading){
return(
this.renderLoadingView()
);
}
else{
return(
this.renderLoadedView()
);
}
}
}
var style = StyleSheet.create({
});