Leveraging webpack alongside url-loader for embedding images within React applications

When styling with an inline style and passing in the URL of an image file, I typically do it as shown below:

let url = `url(${this.state.logo})`
        var cardStyle = {
            backgroundImage: url,
            backgroundSize: '200px 50px',
            backgroundRepeat: 'no-repeat'
        }

To use this style in a div element, simply include it like so:

<div className='work-card' style={cardStyle}></div>

The URL is usually passed as a property such as '../images/logos/ciena.png', which represents the relative path to the image from the component.

However, when running the app using webpack, a 404 error is encountered for the image. The error message appears as follows:

http://localhost:8080/images/logos/ciena.png 404 (Not Found)

I have been successfully loading images using url-loader in scss files, but encountering issues when using it inline. Can anyone provide guidance on how to resolve this issue?

Below is my Webpack configuration:

const HtmlWebPackPlugin = require("html-webpack-plugin");

const htmlWebpackPlugin = new HtmlWebPackPlugin({template: "./src/index.html", filename: "./index.html"});

module.exports = {
    output: {
        publicPath: "/"
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            }, { // regular scss files to css
                test: /\.scss$/,
                loader: 'style-loader!css-loader!sass-loader'
            }, {
                test: /\.(jpe?g|png|gif|svg)$/i,
                loader: 'url-loader',
                options: {
                    limit: 8000, // Convert images < 8kb to base64 strings
                    name: 'images/[name].[ext]'
                }
            }, {
                test: /\.(pdf|docx)$/,
                loader: 'file-loader?name=documents/[name].[ext]',
            }
        ]
    },
    devServer: {
        historyApiFallback: true
    },
    plugins: [htmlWebpackPlugin]
};

Your assistance is greatly appreciated!

Answer №1

In order to solve the issue, make sure to update your url-loader configuration like this:

{
  test: /\.(gif|png|jpg|svg)(\?.*$|$)/,
  use: [
    {
      loader: 'url-loader',
      options: {
        limit: 8192,
        name: '[name].[ext]',
        publicPath: 'images/'
      },
    },
  ],
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Excel document became corrupted after downloading through a ReactJs jQuery ajax post request

Attempting to download a file using jQuery AJAX post request from ReactJs, with an express router middleware layer utilizing the Request API to send requests to a Spring Boot REST API. The flow goes like this: AJAX => Express POST route => Spring Boo ...

It appears that Apexcharts is not compatible with React/Next.js

Issue Encountering a crash in my Next.js/React/Node application whenever I utilize import Chart from "react-apexcharts" in any file. Upon attempting to access the app, an error message is displayed: Server Error ReferenceError: window is not ...

Is there a way to include a button at the top of the Notiflix.Loading() overlay for closing or stopping it?

I've integrated the "notiflix" library into my project, and I'm currently using notiflix.loading.pulse() for a lengthy process. While this works perfectly fine, I would like to add a button (for closing/stopping the process) on top of the loading ...

I am unable to reach POST; instead, I keep receiving GET

After deciding to expand my knowledge, I delved into the world of NodeJS and ReactJS, excited about learning something new. However, there is a dilemma that requires assistance. On the server side, I installed several packages such as MySQL, body-parser, n ...

Change the class upon clicking the element

Looking to create a function that toggles classes on elements when specific links are clicked. For example, clicking on link 1 should add the "active" class to the red element, while clicking on link 2 should do the same for the pink element, and so forth. ...

"Troubleshooting a problem with ReactJS functional component props within the useEffect hook in

In my code, I am utilizing a functional component as a child and passing props from the parent. Within these props is an array called value, which initially starts off empty([]) when accessed inside the useEffect hook. However, after some time, this arra ...

React: incrementing state values

Why am I receiving a "do not mutate" warning when using SetState with "++", yet no warning appears when setting it with "+1"? Can you explain why this discrepancy occurs? ...

Getting the initial date of the upcoming month in JavaScript

I'm trying to figure out how to get the first day of the next month for a datePicker in dd/mm/yyyy format. Can anyone help? Here's the code I currently have: var now = new Date(); if (now.getMonth() == 11) { var current = new Date(now.getFu ...

Adjust CKEditor's height within Vue.js

I recently began experimenting with integrating ckeditor5 into a Vue.js project. However, I encountered an issue where I couldn't manually adjust its height. Below is the code snippet I used - could you please review it and let me know if there are an ...

Adjust the checkmark color of MUI Checkbox

When using Material UI's MUI library for React, I encountered an issue with the checkbox checkmark color. By default, the checkmark takes on the background color of the container element, which is great for light backgrounds but not ideal for dark one ...

The Apollo Client mutation input type is missing data

Currently, I am working with Apollo-client and facing an issue while making a mutation on the client. It seems that when I perform my mutation, the data being passed to the server becomes void. Below is my mutation type: type: recipeType, args:{ ...

Am I on the right track with incorporating responsiveness in my React development practices?

Seeking advice on creating a responsive page with React components. I am currently using window.matchMedia to match media queries and re-rendering every time the window size is set or changes. function reportWindowSize() { let isPhone = window.matchMed ...

WebPack Error: When calling __webpack_modules__[moduleId], a TypeError occurs, indicating that it is not a function during development. In production, an Invalid hook call error

Encountering a WebPack error when utilizing my custom library hosted as a package and streamed with NPM Link. Interestingly, the production version functions flawlessly. Below are my scripts: "scripts": { "dev": "rm -rf build ...

Arranging divs within a wrapper, ensuring that one of them displays a vertical scrollbar when the content exceeds the space available

I'm currently facing a challenge with defining the height of the description box in order to achieve the layout shown. I am trying to find a solution without relying on javascript. https://i.stack.imgur.com/3j278.png At present, the wrapper and titl ...

Struggling to eliminate the underlines from an HTML hyperlink

Can someone help me figure out how to remove the annoying underline link that pops up when hovering over an a element in HTML? I attempted adding a style="text-decoration: none" attribute to the a link, but the underline persists when I hover over the text ...

Elevated UI Kit including a setFloating function paired with a specialized component that can accept

I am currently experimenting with using Floating UI alongside various custom React components. These custom components create internal element references for tasks like focus and measurements, but they also have the capability to accept and utilize a RefOb ...

Having trouble accessing a React component class from a different component class

I just started learning reactjs and javascript. For a simple project, I'm working on creating a login and registration form. The issue I'm facing is that when a user enters their email and password and clicks 'register', instead of movi ...

Utilizing external CSS to style an SVG file within an HTML document

Hello there, I have a collection of SVG files that I need to dynamically modify the fill color of, preferably using CSS. Here is the structure: <div> <svg width="100%" height="100%" viewbox="0 0 64 64" preserveAspectRatio="xMinYMin m ...

Beware, search for DomNode!

I attempted to create a select menu using material-ui and React const SelectLevelButton = forwardRef((props, ref) => { const [stateLevel, setStateLevel] = useState({ level: "Easy" }); const [stateMenu, setStateMenu] = useState({ isOpen ...

Is it possible to streamline the restart process in my game and eliminate the extra unnecessary click?

This game requires you to click each image once without clicking one twice. The issue arises when trying to reset the game after all images are clicked. Currently, it requires an extra random click after all 12 images have been clicked in order to render t ...