Usually, when I use images for any web applications, I use google images where I am able to copy the image address. But, I recently ran into a problem trying to upload an image from my laptop. So after spending hours trying to import my local image to in the react component, I cam across many ways to make it work. But some of them didn't work on the deployed version.
But with this particular method that I'm about to write about, my images were still visible after deploying my website.
So let's get started!
First you need to install file-loader: npm install --save-dev file-loader
and then, in your webpack.config.js
inside rules
add this:
rules: [
{ test: /\.(png|jpe?g|gif)$/i, loader: 'file-loader' },
],
Then, make sure you have your desired image saved in an image
folder.
public
|____index.html
src
|____components
| |____component1.js
|
|____images
|____meme.jpeg
Now, in your component, you can import your image:
import React, { Component } from 'react'
import meme from '../Images/meme.jpeg'
class LocalImageInReact extends Component {
render() {
return (
<div>
<h1>Using a local image in React!</h1>
<img src={meme} alt="issa meme"/>
</div>
)
}
}
And that is it! You have successfully imported a local image in your react component which will work in the deployed version too!
Thank you :)
Top comments (2)
What does file-loader do in this case?
I believe that the file-loader allows you to import the image in the react component