Search code examples
androidreact-nativereact-native-cli

Why react native can`t find image in assets folder?


I have a background image in src/assets folder which I try to get access to from src/screens/splash/index.js as such:

import {ImageBackground} from 'react-native';
import React from 'react';

export default function SplashScreen() {
  return (
    <ImageBackground
      source={require('../../assets/bg1.jpg')}
      resizeMode={'cover'}
      style={{flex: 1}}>
    </ImageBackground>
  );
}

Returns this error:

None of these files exist:

  • bg1.jpg
  • src\assets\bg1.jpg\index(.native|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)

If i move the image in any other folder, for example screens and change source to:

source={require('../../screens/bg1.jpg')} 

its working fine. Im baffled and wondering the reason behind it? Is it maybe because I use react-native cli and renamed the tsx file created originally to js? Here is a picture in case it helps understanding the problem.

enter image description here


Solution

  • After trying everyting was suggested in the comments, nothing has worked so far. I went ahead and continue building the app (following a tutorial) and re-compiled the application, now on an other computer and it started working!

    The only change that I made since added the assets folder and the image that following the documentation integration-with-android-fragment I added few extra lines to MainActivity.java as suggested.

    import android.os.Bundle;
    

    and

      private Bundle getLaunchOptions(String message) {
        Bundle initialProperties = new Bundle();
        initialProperties.putString("message", message);
        return initialProperties;
    }
    

    Now im not 100% sure this was the solution to the problem, but I assume it must have been as no other changes has been made to the code since the error message appeared..

    That is also possible that on my other computer it still wouldnt work, so the error is rooted somewhere within how my computer handeled these packadges. Unfortunately Im unable to test this theory for the next 2 weeks, but will share it whatever it concludes.