Reputation: 21
I am having trouble having an image show up on my personal website. I am using React to display each page on my site. On my AboutMe Page, I have successfully imported an image and have displayed it correctly, where Webpack had no problem building and finding the image. As you can see below, this is what I wrote:
import img from '../../../public/assets/images/linked-in-profile.jpg'
<Col>
<img className="about-image" src={img} />
</Col>
However, on my Projects page, I am trying to have Bootstrap cards that contain images. I followed the same steps that I did on my AboutMe page; I imported the image and added my tag inside my card. When I check my site running on a localhost, the image does not show, and my console reports an error with ":8080/public/Floor-Is-Lava.jpg:1 GET http://localhost:8080/public/Floor-Is-Lava.jpg 404 (Not Found)"
The code on this page is:
import img from '../../../public/floor-is-lava.jpg'
<Card bg="light" text="secondary" style={{ width: '350px', height: '300px' }}>
<img className="project-img" src={img} />
<Card.ImgOverlay>
<Card.Text>Go to github</Card.Text>
</Card.ImgOverlay>
</Card>
The error directs to this snippet of code in my server/index.js:
// any remaining requests with an extension (.js, .css, etc.) send 404
app.use((req, res, next) => {
if (path.extname(req.path).length) {
const err = new Error('Not found')
err.status = 404
next(err)
} else {
next()
}
})
My Webpack says that all my images were successfully built, but I have no clue why only one shows up on my site.
Any help would be greatly appreciated!
Upvotes: 2
Views: 9702
Reputation: 11
I just had this problem with my React App that I built using Webpack config 4x. I spent a few hours but eventually got this working now.
const path = require('path');
const DIST_DIR = path.resolve(__dirname, 'public');
const SRC_DIR = path.resolve(__dirname, 'src');
module.exports = {
entry: SRC_DIR + '/app/',
output: {
path: DIST_DIR + "/build",
filename: 'bundle.js'
},
devServer: {
port: 3333,
contentBase: DIST_DIR + "/build",
inline: true
},
module: {
rules: [{
test: /\.(js|jsx|png|jpg|svg|gif|ico)$/,
exclude: /node_modules/,
use: "babel-loader"
},
{
test: /\.(png|svg|jpg|jpeg|gif|ico)$/,
use: [{
loader: 'url-loader',
options: {
limit: 10000,
}
}],
},
{
test: /\.css$/,
use: 'css-loader'
},
]
}
};
In my component file:
import imageToRender from '../../assets/images/some.jpg';
...
...
<div>
<img src={imageToRender}/>
</div>
Upvotes: 1
Reputation: 442
You are getting that error because you are referencing public directory images.
Copy your image to src directory and import it. then it might work.
import img from '../../floor-is-lava.jpg'
<Card bg="light" text="secondary" style={{ width: '350px', height: '300px' }}>
<img className="project-img" src={img} />
<Card.ImgOverlay>
<Card.Text>Go to github</Card.Text>
</Card.ImgOverlay>
</Card>
Please let me know if you have any issues.
Upvotes: 1