'How to display image from src/images without using import at the top and without using public directory in react/reactjs
I want to render the star1.png located in src/images/ directory without using import at the top and without using the public directory.
My code:
import React from "react"
import ReactDOM from "react-dom"
class App extends React.Component
{
render(){
let starIcon = "./images/star1.png"
return(
<>
<h1>Hello</h1>
<img src={starIcon} />
</>
)
}
}
ReactDOM.render(<App />, document.getElementById("root"))
Solution 1:[1]
I found the answer to my question which is using require:
let starIcon = require("./images/star1.png")
Solution 2:[2]
I'm not sure if I understand your question fully, but you could pass the image as a blob through props and set that blob as the source of the image.
Solution 3:[3]
The problem is related to the prod build I think because when you created a build asset directory will not copy.
Solutions:
- You can import it'll be added to the bundle it'll work
- You can move to the public it'll also be added in the build/dist directory
- You can manually/automatically copy assets to the build/dist directory.
The last solution you are looking I think.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tenshi |
| Solution 2 | R. Boudewijn |
| Solution 3 | Rahul Sharma |
