Import local images in React

bhuma08

bhuma08

Posted on October 24, 2020

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 :)

💖 💪 🙅 🚩
bhuma08
bhuma08

Posted on October 24, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related