1

I can't view the photos in my project that I created with create react app. please help me..

<img id="2" src={require('../../../img/logo.png')} className="img-fluid" alt="logo"/>

the file path is absolutely correct.

package.json:

{
  "name": "e-ticaret-react-ui",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.15.0",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "axios": "^0.24.0",
    "bootstrap": "^5.1.3",
    "jquery": "^3.6.0",
    "react": "^17.0.2",
    "react-bootstrap-icons": "^1.6.1",
    "react-dom": "^17.0.2",
    "react-redux": "^7.2.6",
    "react-router-dom": "^5.3.0",
    "react-scripts": "4.0.3",
    "redux": "^4.1.2",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

A photo was displayed in the React project created by Visual Studio. Photos are not displayed in the project I created with create react app in vs code. The file structure is exactly the same. the folder paths are correct.

maria
  • 57
  • 5
  • 1
    Try `require('../../../img/logo.png').default` – kiranvj Nov 03 '21 at 12:45
  • add your image inside the public folder (or create an images folder in public and add your image in it ). in your tag use `` – sojin Nov 03 '21 at 12:45
  • @kiranvj thanks. it worked. So why do we need to write "default"? – maria Nov 03 '21 at 12:48
  • Does this answer your question? [How to import image (.svg, .png ) in a React Component](https://stackoverflow.com/questions/43823289/how-to-import-image-svg-png-in-a-react-component) – Dmitriif Nov 03 '21 at 12:59
  • @maria [this](https://stackoverflow.com/questions/43247696/javascript-require-vs-require-default) will give some insights – kiranvj Nov 03 '21 at 13:10

2 Answers2

0

Try this:

At the top of your file with your imports use this line:

import Logo from '../../../img/logo.png';

And then your img would look like this:

<img id="2" src={ Logo } className="img-fluid" alt="logo"/>
Pan Vi
  • 627
  • 6
  • 17
Shaded
  • 158
  • 1
  • 9
  • Since I call all the photos with the require method, a solution is needed accordingly. but adding ".default" to the end of require fixed it. anyway thanks for your solution – maria Nov 03 '21 at 12:50
0

Create a folder calls assets then put on their images inside, like this:

import Logo from '../../assets/logos/logo.png';

<img id="2" src={ Logo } className="img-fluid" alt="logo"/>
rnewed_user
  • 1,386
  • 7
  • 13