In my React Native app, I am fetching images from an API with unknown dimensions. How do I auto scale the height if I know my desired width?
Example:
I set the width to Dimensions.get('window').width
. How do set the height and keep the same ratio?
export default class MyComponent extends Component { constructor(props) { super(props) this.state = { imgUrl: 'http://someimg.com/coolstuff.jpg' } } componentDidMount() { // sets the image url to state this.props.getImageFromAPi() } render() { return ( <View> <Image source={uri: this.state.imgUrl} style={styles.myImg} /> <Text>Some description</Text> </View> ) } } const styles = StyleSheet.create( myImg: { width: Dimensions.get('window').width, height: >>>???what goes here???<<< } )
To set image width to be 100% and height to be auto in React Native, we can set the width and height of the Image . to call Dimensions. get with 'window' to get the window's dimension. Then we calculate the ratio between the width and height of the image with win.
This component provides you a simple way to load a remote image and automatically set Image height to the image dimension which fits the provided width. React Native Image component needs users to set both width and height props.
Try this:
import React, { Component, PropTypes } from "react"; import { Image } from "react-native"; export default class ScaledImage extends Component { constructor(props) { super(props); this.state = { source: { uri: this.props.uri } }; } componentWillMount() { Image.getSize(this.props.uri, (width, height) => { 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 }); } }); } render() { return ( <Image source={this.state.source} style={{ height: this.state.height, width: this.state.width }} /> ); } } ScaledImage.propTypes = { uri: PropTypes.string.isRequired, width: PropTypes.number, height: PropTypes.number };
I'm passing the URL as a prop called uri
. You can specify your width
prop as Dimensions.get('window').width
and that should cover it.
Note that this will also work if you know what you want to set the height to and you need to resize the width to maintain the ratio. In that case, you would specify the height
prop instead of the width
one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With