-1

I have the following basic react native code:

enter image description here

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

//images
import login_blueGirl from './assets/images/login_blueGirl.png';


const App = () => {
  return (
    <>
     <View style={styles.container}>
        <Image source={login_blueGirl}></Image>
     </View>
    </>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column'
  }
});

export default App;

I'm getting a Cannot find module './assets/images/login_blueGirl.png'. When I type ./ VSCode give me however the autocomplete option:

enter image description here enter image description here

Any clue on why this is happening?

Shury
  • 468
  • 3
  • 15
  • 49

3 Answers3

2

That's not quite how you're supposed to be importing images, use require instead.

const App = () => {
    return (
        <View style={styles.container}>
            <Image source={require("./assets/images/login_blueGirl.png")} />
        </View>
    );
};
emeraldsanto
  • 4,330
  • 1
  • 12
  • 25
2

You can specify the width and height of the image to display it, do this:

const App = () => {
  return (
    <View style={styles.container}>
      <Image style={{ width: 100, height: 80 }} source={require("./assets/images/login_blueGirl.png")}></Image>
    </View>
  );
};

or

const styles = StyleSheet.create({
    imgStyle: {
        width: 50,
        height: 50,
    }
});

const App = () => {
    return (
        <View style={styles.container}>
            <Image style={styles.imgStyle} source={require("./assets/images/login_blueGirl.png")}></Image>
        </View>
    );
};
emeraldsanto
  • 4,330
  • 1
  • 12
  • 25
1

To import a static file like a .png file, you can declare

const blueGirl = require("assets/images/login_blueGirl.png");

Then you can use it in an Image component

<Image style={styles.image} source={blueGirl} />

Also the image is used as a self closing tag you don't have to add another </Image> tag.

In order to fully understand how tags and syntax work always check out the official documentation React Native API

mcnk
  • 1,690
  • 3
  • 20
  • 29
  • I've done it like this and it still doesn't display the image. Moreover when I hover over const blueGirl = require("assets/images/login_blueGirl.png"); VSCode comments that it should be converted to an import which results in the original line with import: https://i.imgur.com/G7jVimY.png – Shury May 23 '20 at 19:29
  • When you hover on it your default node linter is showing the problem, however, you should add a linting tool for React Native like this one https://medium.com/appstud/setup-eslint-and-prettier-together-for-react-and-react-native-projects-in-visual-studio-code-78772d58358d also please make sure that you set a width and height for the image as well to display it. – mcnk May 23 '20 at 19:43