Search code examples
react-nativebackground

Error: Image: asset with ID "1" could not be found. Please check the image source or packager


I'm new to react native and I'm following a tutorial to learn the language. I'm now trying to set a background image using ImageBackground.

WelcomeScreen.js:

import React from 'react';
import { ImageBackground, StyleSheet } from 'react-native-web';

function WelcomeScreen(props) {
    return (
        <ImageBackground 
            style={styles.background}
            source={require("../assets/background.jpg")}
        ></ImageBackground>
    );
}

const styles = StyleSheet.create({
    background: {
        flex: 1
    }
})

export default WelcomeScreen;

App.js

import React from 'react';
import { View } from 'react-native';
import WelcomeScreen from './app/screens/WelcomeScreen';

export default function App() {

  return (
    <WelcomeScreen />
  );
}

Now I get this error: Error: Image: asset with ID "1" could not be found. Please check the image source or packager.

I have a app folder in in my projectfolder. In this app folder I have the assets folder and a screens folder. The WelcomeScreen.js is in the screens folder. The background.jpg is in the assets folder and the App.js is in the main/project folder.

I can't seem to find any way to fix this error.


Solution

  • Try changing your module import from react-native-web to just react-native

    WelcomeScreen.js

    import React from "react";
    import { ImageBackground, StyleSheet } from "react-native";
    
    function WelcomeScreen(props) {
      return (
        <ImageBackground
          style={styles.background}
          source={require("../assets/background.png")}
        ></ImageBackground>
      );
    }
    
    const styles = StyleSheet.create({
      background: {
        flex: 1,
      },
    });
    
    export default WelcomeScreen;
    

    You do not need to add ./app to your WelcomeScreen.js file path

    App.js

    import WelcomeScreen from "./screens/WelcomeScreen";
    
    export default function App() {
      return <WelcomeScreen />;
    }
    

    Hope this helps!