How to access local image URL in a json file

I have problem in accessing the local image url in a json file. Below are all the approaches I have tried but none of them works.

// json
{
    "image": "./images/example.jpg",
}

// React Native
import data from './data.json';

const URL =  JSON.stringify(data.image)   
<Image source = {{uri: URL } style = {{ width: 98, height: 22 }} />    // Image not showing

const URL = data.image
<Image source = {{uri: URL } style = {{ width: 98, height: 22 }} />    // Image not showing

Image is not showing in the above approaches.

I also tried with require as following:

// json
{
    "image": "example.jpg",
}

const item =  data.image   
<Image source = {require( './images/' +  item)} style = {{ width: 98, height: 22 }} />

const item =  JSON.stringify(data.image) 
<Image source = {require( './images/' +  item)} style = {{ width: 98, height: 22 }} />

The above shows an error of requires only take string literal argument, which is weird to me because the following code actually works.

const item = 'example.jpg'
<Image source = {require( './images/' +  item)} style = {{ width: 98, height: 22 }} />

I been searching on the internet for hours and could not find a solution to it. Can someone show me an correct example to access the local json data? Thanks a lot.

1 answer

  • answered 2018-08-09 04:28 Aravind S

    You cannot use variables in require. All require must be statically analyzable. That means you always have to write require('/path/to/file'). You can try something like

    const images = {
        profile: {
            profile: require('./profile/profile.png'),
            comments: require('./profile/comments.png'),
        },
        image1: require('./image1.jpg'),
        image2: require('./image2.jpg'),
    };
    
    export default images;
    import Images from './img/index';
    
    render() {
        <Image source={Images.profile.comments} />
    }
    

    You can see more about it here

    We intentionally don't support dynamically generated image names because it makes it very hard to manage assets over time, just like how you wouldn't want to do

    var MyComponent = require('./' + libName + typeOfComponent);

    or something like that. Dynamic image name generation like this also won't work with the new dynamic asset managing system we're rolling out which let's you add and update assets on the fly with just cmd+R (no more need to add to Xcode and recompile).