Priyanshu Kumar
Priyanshu Kumar

Reputation: 312

React Native: Image Not Showing

Image is not showing in my app, I have seen its docs too.

Please tell me whats the problem.

Code

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

export default function App() {
  return (
   <View>
   <Image
        style={styles.backgroundImage}
        source={require('./assets/bg.jpg')}
      />
   </View>
  );
}

const styles = StyleSheet.create({
  backgroundImage: {
    height: '100%',
    width: undefined,
    aspectRatio: 1,
    zIndex: 1,
  },
});

Its just showing white screen. Nothing else.

Upvotes: 2

Views: 2106

Answers (1)

m_wer
m_wer

Reputation: 1554

The react-native image component needs to have the size set by pixels.

So your first solution would be to get the dimensions of your screen/window and set the width and height accordingly. So you need to calculate using the aspect ratio. You can also use a resize mode like 'stretch', 'contain', 'cover', etc. as described here

import React from "react";
import { Image, StyleSheet, View, Dimensions} from "react-native";

const dimensions = Dimensions.get('window');
const imageHeight = Math.round(dimensions.width * 9 / 16); //calculate with aspect ratio
const imageWidth = dimensions.width;

function App() {

  return (
    <View>
      <Image
         style={styles.backgroundImage}
         source={require('./assets/bg.jpg')}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  backgroundImage: {
    height: imageHeight,
    width: imageWidth,
    zIndex: 1,
  },
});

export default App;

Second solution: as it seems that you want to set it as background image would be to use the BackgroundImage component as described here

function App() {

  return (
    
      <ImageBackground style={styles.backgroundImage} source={require('./assets/bg.jpg')} />
  );
}

const styles = StyleSheet.create({
  backgroundImage: {
    height: '100%',
    width: undefined,
    aspectRatio: 1,
    zIndex: 1,
  }
});

Upvotes: 2

Related Questions