DEV Community 👩‍💻👨‍💻

Cover image for Import local images in React
bhuma08
bhuma08

Posted on

Import local images in React

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' },
    ],
Enter fullscreen mode Exit fullscreen mode

Then, make sure you have your desired image saved in an image folder.

public
  |____index.html
src
  |____components
  |        |____component1.js
  |  
  |____images
           |____meme.jpeg
Enter fullscreen mode Exit fullscreen mode

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>
        )
    }
}
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
dmahely profile image
Doaa Mahely

What does file-loader do in this case?

Collapse
 
bhuma08 profile image
bhuma08 Author

I believe that the file-loader allows you to import the image in the react component

Classic DEV Post from 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!