Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using require('...') to dynamically import images in react js not working anymore

I have old projects where this works

<img src={require('./logo.svg')} className="App-logo" alt="logo" />

Bu I created a new project with create-react-app and require('...') no longer works. It's like the new version doesn't support require, so how do i load images dynamically ?

Old project package.json

"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.3"
}

New project package.json

"dependencies": {
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.0",
"web-vitals": "^0.2.4"
}
like image 412
Chukwudi Ubah Avatar asked Nov 04 '20 14:11

Chukwudi Ubah


1 Answers

I solved it.

requires('...') now returns an object, So your image will be in default key, like below

<img src={require('./logo.svg').default} className="App-logo" alt="logo" />

I don't know why this was changed tho.

like image 131
Chukwudi Ubah Avatar answered Oct 17 '22 23:10

Chukwudi Ubah