Search code examples
javascriptreact-native

Why does my image disappear when I apply the width attribute?


I'm trying to create an app with react native,

this is the code atm:

import { View, Text, Image } from 'react-native'
import React from 'react'

export default function Login() {
  return (
    <View>
        <Image source={require('./../assets/images/login.jpg')}
            style={{
              width: '100%',      
            }}
        />
    </View>
  )
}

The problem is when I apply the width attribute, because my image just disappear. If I don't use that attribute it's all good, I can use height and it's working properly, but as soon as I use width I just see a white screen. I tried different images, different %, but same result.

PS:This error is only when I use %, if I use px is working.

Can you explain to me why this is happening?

Thank you.

I wanted the image to cover the entire width of the background.


Solution

  • If you want the image to cover the entire width of the background, you can use flex container for your background views and set the image width to 100% to take up the whole container - Try this:

    import { View, Image } from 'react-native';
    import React from 'react';
    
    export default function Login() {
      return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
          <Image 
            source={require('./../assets/images/login.jpg')}
            style={{ width: '100%', height: undefined, aspectRatio: 1 }}
          />
        </View>
      );
    }
    

    You have to define in the view when you use % but px you don't need to define as it was set in the React Native system