Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

javascript - Unable to import image from data.js file in React

This is the entire folder React structure:

enter image description here

I have a data.js file with some data so I can map it dynamically in one of my components.

enter image description here

Upon doing the following code in my component Cities.js:

import React from 'react';
import {countries} from "../database/data"


 function countriesExplain () {
    return (
        <>
        <div className="">
          {countries.map((data, key) => {
            return (
              <div key={key}>
                  <div>
                 { data.countryCapital }
                 </div>
                 <div>
                 { data.cities['id-1'].name }
                 </div>
                 <div>
                 { data.cities['id-1'].src }
                 </div>
              </div>
            );
          })}
        </div>
      </>
    );
}

export default countriesExplain;

When mapping through the data to show the image I am getting this error on the FrontEnd

enter image description here

What am I doing wrong? The image path seems to be correct in my view so I am not sure why am I not getting the image on my frontend.

Thanks

question from:https://stackoverflow.com/questions/65858373/unable-to-import-image-from-data-js-file-in-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should place your images folder into the public folder. Also, change the line:

"src": require("../images/merbourne-city.jpg")

to

"src": "/images/merbourne-city.jpg".

Note: The code in countriesExplain.js will display the path of the image. If you want to display the image, you should replace the div with img tag.

data.js

  "cities": {
      "id-1": {
        "name": "Melbpurne",
        "src": "/images/merbourne-city.jpg"
      }
    }

countriesExplain.js

import React from 'react';
import {countries} from "../database/data"


 function countriesExplain () {
    return (
        <>
        <div className="">
          {countries.map((data, key) => {
            return (
              <div key={key}>
                  <div>
                 { data.countryCapital }
                 </div>
                 <div>
                 { data.cities['id-1'].name }
                 </div>
                 <img src={ data.cities['id-1'].src }/>
              </div>
            );
          })}
        </div>
      </>
    );
}

export default countriesExplain;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...