1

I am new to ReactJS and I can't seem to figure out where to "require" the images I need.

import React, { Component } from 'react';

class ClothesFrame extends Component{
state = {
    /*clothesimages: {  //this works
        hat: require("./img/hat.svg"),
        scarf: require("./img/scarf.svg")
    },*/
    outfit: require('./outfit.json'),
    clothesimages: (function()    //this does not
    {
        let outfit = require('./outfit.json');
        let result = {};
        for(var garment in outfit)
        {
            for(var prop in outfit[garment])
            {
                if(prop == "img")
                {
                    result[garment] = require(outfit[garment][prop]);  //Cannot find module './img/hat.svg'
                }
            }
        }
        return result;
    })()
}

constructor(props){
    super(props);
    this.getClothes = this.getClothes.bind(this);
    this.getClothesStr = this.getClothesStr.bind(this);
    this.isInBoundaries = this.isInBoundaries.bind(this);
}

I get the error "Cannot find module './img/hat.svg'" when I try to load the images from a path specified in a JSON file. The first clothesimages works just fine but the second gives me the error. I want to be able to load the images from a path in a JSON file rather than in the code itself. My only incling is that the value of the second clothesimages is actually worked out later than it otherwise would be.

1 Answer 1

0

here

result[garment] = require(outfit[garment][prop]);  

outfit[garment][prop] is replaced with ./img/hat.svg. and there is nothing at that path. you need to create img folder in the current folder and place hat.svg there to make it work

here you can do this. I got the same issue in the past and it worked for me

 if(prop == "img")
                {
                  const imgName=outfit[garment][prop].split('/').slice(-1)[0]

                    result[garment] = require(`./img/${imgName}`);  
                }
Sign up to request clarification or add additional context in comments.

3 Comments

But there is something in that folder, as you can see the first clothesimages works with "hat: require('./img/hat.svg')"
it's beyond me too. As both ways use dynamic urls. what's the difference in it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.