Reputation: 179
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"
}
Upvotes: 5
Views: 2148
Reputation: 179
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.
Upvotes: 9
Reputation: 6819
You can import an image the following way then
import Logo from "./logo.svg";
<img src={Logo} className="App-logo" alt="logo" />
Upvotes: 0