This is covered in the documentation under the section "Static Resources":

The only allowed way to refer to an image in the bundle is to literally write require('image!name-of-the-asset') in the source.

// GOOD
<Image source={require('image!my-icon')} />

// BAD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('image!' + icon)} />

// GOOD
var icon = this.props.active ? require('image!my-icon-active') : require('image!my-icon-inactive');
<Image source={icon} />

However you also need to remember to add your images to an xcassets bundle in your app in Xcode, though it seems from your comment you've done that already.

http://facebook.github.io/react-native/docs/image.html#adding-static-resources-to-your-app-using-images-xcassets

Answer from Colin Ramsay on Stack Overflow
Top answer
1 of 16
109

This is covered in the documentation under the section "Static Resources":

The only allowed way to refer to an image in the bundle is to literally write require('image!name-of-the-asset') in the source.

// GOOD
<Image source={require('image!my-icon')} />

// BAD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('image!' + icon)} />

// GOOD
var icon = this.props.active ? require('image!my-icon-active') : require('image!my-icon-inactive');
<Image source={icon} />

However you also need to remember to add your images to an xcassets bundle in your app in Xcode, though it seems from your comment you've done that already.

http://facebook.github.io/react-native/docs/image.html#adding-static-resources-to-your-app-using-images-xcassets

2 of 16
97

RELEVANT IF YOU HAVE KNOWN IMAGES (URLS):

The way I hacked my way through this problem:

I created a file with an object that stored the image and the name of the image:

export const ANIMAL_IMAGES = {
  dog: {
    imgName: 'Dog', 
    uri: require('path/to/local/image')
  },
  cat: {
    imgName: 'Cat on a Boat', 
    uri: require('path/to/local/image')
  }
}

Then I imported the object into the component where I want to use it and just do my conditional rendering like so:

import { ANIMAL_IMAGES } from 'path/to/images/object';

let imgSource = null;

if (condition === 'cat') {
  imgSource = ANIMAL_IMAGES.cat.uri;
}

<Image source={imgSource} />

I know it is not the most efficient way but it is definitely a workaround.

Hope it helps!

๐ŸŒ
Reddit
reddit.com โ€บ r/reactnative โ€บ dynamic path using require in rn image component
Dynamic path using require in RN Image component : r/reactnative
February 29, 2024 - Looks like dynamic require paths are a no-go in React Native. You can try using the 'source' prop of Image component with a network request to fetch the image instead.
Discussions

React Native: require() with Dynamic String?
I have read on some threads that this is a bug in React Native and in others that this is a feature. Is there a new way to require a dynamic resource within a function? ... React's require() only uses static url not variables, that means that you have to do require('/path/file'), take a look ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to use require with a path passed from a different file for an image?
As long as metro is involved, you cannot require a file with a dynamic path. You must pass the path as a string. Even a path like ./assets/${img}.png won't work. See this discussion for more details : https://github.com/facebook/react-native/issues/6391 As a workaround, you can require all your images in variables and re-use those in your code. More on reddit.com
๐ŸŒ r/reactnative
2
1
March 5, 2024
Dynamic import path for React Native - javascript
I want to do is I want to import React-Native dynamic path. example: import Demo from `./screens/${path}`; I found one method using lazy, but it also only working when initialize const variable like More on stackoverflow.com
๐ŸŒ stackoverflow.com
April 19, 2024
React Native: how to use require(path) with dynamic urls?
I want to use WebView to show some html content here is an example: return ( More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
GitHub
github.com โ€บ facebook โ€บ react-native โ€บ issues โ€บ 6391
Require file dynamically by variable ยท Issue #6391 ยท facebook/react-native
March 9, 2016 - I want to require files like: var component = require("myApp/components/" + name); Seems like require wants passed string to be static, not dependent on any runtime actions. var name = "myComponent"; var component = require("myApp/compon...
Author ย  pie6k
๐ŸŒ
LogRocket
blog.logrocket.com โ€บ home โ€บ natively implement dynamic imports in react native
Natively implement dynamic imports in React Native - LogRocket Blog
June 4, 2024 - Provide the loader property with a function that imports your target component (replace './YourComponent' with the actual path to your component) and specify the loading property to display the loading component during the loading process ยท Finally, use the DynamicComponent within your appโ€™s UI. It will dynamically load the target component and display it once itโ€™s ready, showing the loading component in the meantime ยท This library was originally designed for React web applications, so it may not always work well in React Native.
๐ŸŒ
Medium
medium.com โ€บ @dannyhyunsoowilliams โ€บ dynamic-imports-supported-in-react-native-e839f6481eb2
Dynamic imports supported in react native | by Danny Williams | Medium
July 26, 2023 - Historically for react native weโ€™ve never been able to do dynamic imports, neither based on a variable or a regex. However this kind of functionality has been in webpack and other web bundlers for some time. Now that we have access to require.context we can build tools like storybook and expo router without needing to generate imports at build time, we can instead dynamically import them at runtime.
๐ŸŒ
YouTube
youtube.com โ€บ watch
#65 Dynamic Path For Local Assets Images In React Native - YouTube
Hi guys, In this video I have explained the good and bad ways to load local images url dynamically. I hope you will like my video.#DynamicLocalImagesPath #Lo...
Published ย  November 23, 2020
Top answer
1 of 11
45

React's require() only uses static url not variables, that means that you have to do require('/path/file'), take a look at this issue on github and this one for more alternative solutions, there are a couple of other ways to do it! for e.g

const images = {
profile: {
    profile: require('./profile/profile.png'),
    comments: require('./profile/comments.png'),
},
   image1: require('./image1.jpg'),
   image2: require('./image2.jpg'),
};

export default images;

then

import Images from './img/index';

render() {
    <Image source={Images.profile.comments} />
}

from this answer

2 of 11
22

Here is my solution.

Setup

File structure:

app  
  |--src
    |--assets
      |--images
        |--logos
          |--small_kl_logo.png
          |--small_a1_logo.png
          |--small_kc_logo.png
          |--small_nv_logo.png
          |--small_other_logo.png

        |--index.js
    |--SearchableList.js

In index.js, I have this:

const images = {
  logos: {
    kl: require('./logos/small_kl_logo.png'),
    a1: require('./logos/small_a1_logo.png'),
    kc: require('./logos/small_kc_logo.png'),
    nv: require('./logos/small_nv_logo.png'),
    other: require('./logos/small_other_logo.png'),
  }
};

export default images;

In my SearchableList.js component, I then imported the Images component like this:

import Images from './assets/images';

I then created a new function imageSelect in my component:

imageSelect = network => {
  if (network === null) {
    return Images.logos.other;
  }

  const networkArray = {
    'KL': Images.logos.kl,
    'A1': Images.logos.a1,
    'KC': Images.logos.kc,
    'NV': Images.logos.nv,
    'Other': Images.logos.other,
  };

  return networkArray[network];
};

Then in my components render function I call this new imageSelect function to dynamically assign the desired Image based on the value in the this.state.network:

render() {
  <Image source={this.imageSelect(this.state.network)} />
}

The value passed into the imageSelect function could be any dynamic string. I just chose to have it set in the state first and then passed in.

I hope this answer helps. :)

Find elsewhere
๐ŸŒ
Code Buckets
codebuckets.com โ€บ 2022 โ€บ 03 โ€บ 12 โ€บ dynamic-images-in-react-native
Working with Dynamic Images in React Native โ€“ Code Buckets
October 8, 2022 - React Native doesnโ€™t deal with dynamic images, only static images. Therefore, you have to front up all the images โ€“ you cannot construct the name and path dynamically. The solution Iโ€™ve employed is to hide the dirty details in a static ...
๐ŸŒ
Reddit
reddit.com โ€บ r/reactnative โ€บ how to use require with a path passed from a different file for an image?
r/reactnative on Reddit: How to use require with a path passed from a different file for an image?
March 5, 2024 -

I have an image path in a different file as a string, which I want to pass to another component and then pass into the source of an image.

So basically I want to get path information like from imagePath1 from a different file.

const imagePath1 = '../assets/metaformTools_colorful_choices_big_web.jpg';
const imagePath2 = value.picture;

When I console.log imagePath1 and imagePath2 are the same (true):

console.log(imagePath === imagePath2)

Here only imagePath1 works, although they should be the same

Works:

<ImageBackground style={styles.imageBackground} source={require('imagePath1')} />

Does not work:

<ImageBackground style={styles.imageBackground} source={require('imagePath2')} />

I saw that a lot of people have this problem when googling, unfortunately I did not find a solution which worked and did not really understand the problem.

Would be happy if someone could help! (bear with me, I am a beginner)

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 78352845 โ€บ dynamic-import-path-for-react-native
Dynamic import path for React Native - javascript
April 19, 2024 - const demo = 'Path'; // Your dynamic path variable // Construct the path to your component let componentPath = `../Screen/${demo}`; // Dynamically requires the component using the constructed path const DynamicComponent = require(componentPath).default; // Render the dynamically imported component <DynamicComponent />
Top answer
1 of 5
16

From Marc Shilling's answer on https://github.com/facebook/react-native/issues/3099

You can use an absolute path on imports/requires:

import {ProximaNovaText} from 'MyApp/src/components'; require('MyApp/src/utils/moment-twitter');

where 'MyApp' is whatever name you registered in your index.ios.js file

Note for VS Code: This works, but be warned that you might lose intellisense and cmd/ctrl + click. Thanks Johan for the info about CS code

2 of 5
10

You can mark a directory as a package by adding a package.json within the root directory you want to resolve.

e.g:

- app
    - package.json     // โ† Add this package.json file
    - config
    - components
    - ... (etc)

package.json should look like this:

{ "name": "app" }

Restart your packager

react-native start --reset-cache

Now you can use the following in all of you project files:

import store from 'app/config/store';
import Button from 'app/components/Button';

You can use this same method across other directories in your project, I don't think this works via require, although image paths seemed work.


As noted in the comments, you may lose auto-complete in your editor (VSCode).

For Jetbrains IDE's there are some ongoing tickets here:

  • https://youtrack.jetbrains.com/issue/WEB-17254
  • https://youtrack.jetbrains.com/issue/WEB-20104#comment=27-1486526
  • https://intellij-support.jetbrains.com/hc/en-us/community/posts/205434510-Configure-custom-modules-resolve-folder

This might help with Jetbrains IDE's in the meantime.

// A slash may allow auto-complete to work in your IDE (but will fail to resolve)
import Button from '/app/components/Button'; // Cannot be resolved
๐ŸŒ
DEV Community
dev.to โ€บ kevilondo โ€บ display-images-dynamically-from-a-variable-in-react-native-524g
Display images dynamically (from a variable) in React Native - DEV Community
October 24, 2023 - const my_variable = require('../assets/image.jpg'); <Image source={my_variable} /> Doing this will definitely solve your problem and If you have any question regarding React Native or this specific post, feel free to ask, who knows, maybe other developers are going through the same problem and discussing certain issues here might help a lot of people.
๐ŸŒ
Nkaushik
nkaushik.com โ€บ react-native โ€บ dynamic-image-source-in-react-native
How to add dynamic image source in react native | N Kaushik
July 27, 2020 - const getImage = name => { switch (name) { case "logo": return require("../../images/logo.png") default: return require("../../images/thumbnail.png") } }
๐ŸŒ
DEV Community
dev.to โ€บ dannyhw โ€บ dynamic-imports-supported-in-react-native-273j
Dynamic imports supported in react native - DEV Community
July 26, 2023 - Historically for react native we've never been able to do dynamic imports, neither based on a variable or a regex. However this kind of functionality has been in webpack and other web bundlers for some time. Now that we have access to require.context we can build tools like storybook and expo router without needing to generate imports at build time, we can instead dynamically import them at runtime.
๐ŸŒ
Medium
careerwithvasanth.medium.com โ€บ how-to-use-local-images-dynamically-in-react-native-71b9f3b0db20
How to use local Images dynamically in React Native | by Vasanth Bhat | Medium
May 16, 2020 - โ€œThe only allowed way to refer ... Image path has to be specified during the compilation itself, anything specified dynamically is considered as an error....
๐ŸŒ
React Native
reactnative.dev โ€บ docs โ€บ images
Images ยท React Native
February 20, 2026 - For example, the result of require('./my-icon.png') might be: ... In React Native, one interesting decision is that the src attribute is named source and doesn't take a string but an object with a uri attribute.
๐ŸŒ
Peaku
peaku.co โ€บ questions โ€บ 11423-reaccionar-nativo:-require-()-con-cadena-dinamica
React Native: require() with Dynamic String? - PeakU
April 12, 2022 - I have read on some threads that this is a bug in React Native and in others that this is a feature. Is there a new way to require a dynamic resource within a function? ... As i have heard of, react's require() only uses static url not variables, that means that you have to do require('/path/file'), take a look at this issue on github and this one for more alternative solutions, there are a couple of other ways to do it!
๐ŸŒ
Reddit
reddit.com โ€บ r/reactnative โ€บ react native: dynamic image require in component?
r/reactnative on Reddit: React Native: dynamic image require in component?
December 2, 2020 -

Hi everybody, I'm trying to show a randomly generated image in my Image component, however I'm getting the following error:

invalid call at line 58:require(getRandomImage())

My component:

const [ randomImages, setRandomImages ] = useState([
        //require('../assets/images/aranda.jpg'),
        require('@assets/images/bilmore.jpg'),
        require('@assets/images/cachalote.jpg'),
        require('@assets/images/lola.jpg'),
        require('@assets/images/meson.jpg'),
        require('@assets/images/paloma.jpg'),
        require('@assets/images/picasso.jpg'),
        require('@assets/images/pimpi.jpg'),
        require('@assets/images/tintero.jpg'),
        require('@assets/images/tropicana.jpg'),
    ]);

const getRandomImage = () =>
    {
        return randomImages[rand(0,9)];
    };

    const rand = (min, max) => 
    {
        return Math.floor(Math.random() * (max - min)) + min;
    }


<Image style={{ width:'100%', height:200,}}  resizeMode="cover" source={require(getRandomImage())}/>