Having trouble displaying a background image on a React application

Public>images>img-2.jpg

src>components>pages>Services.js>

      import React from 'react';       
      import '../../App.css';

      export default function Services() {
       return <h1 className='services'>SERVICES</h1>;
      }

src>>App.css>

      .services {
       background-image: url('/images/img-2.jpg');
      }

src>App.js>

      import React from "react";
      import './App.css';
      import Navbar from "./components/Navbar";
      import {Routes, Route} from 'react-router-dom';
      import Services from './components/pages/Services';

      function App(){
       return(
             <>
              <Navbar />
               <Routes>
                <Route path='/services' element={<Services />} />
               </Routes>
             </>
            )
      };

This code was written without any errors, but the image is not displaying. Screenshot(Failed to compile)

The images are not showing up on my website. Can anyone suggest a solution for this issue? Your help would be greatly appreciated.

Answer №1

It is not advisable to store your images in the public folder. When incorporating CSS within the src folder, it's best to utilize relative paths to the image files. React will handle and update the paths to their respective build locations during compilation.

Source: https://github.com/facebook/create-react-app/issues/1248#issuecomment-266313612

If you choose to store your images in the public folder, you can try using '../../../../Public/images/img-2.jpg' as the path. However, it is recommended to keep images inside the src folder and allow React to manage them during the compilation process.

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

Enhance User Experience with Material UI Hover Text on Input Fields

I have been incorporating Material UI controls into my React project, like: TextField Switch DateTimePicker RadioGroup Is there a hover text feature available for these fields? I'm looking for some helper text to appear when hovering over the contro ...

Troublesome button issue encountered in ReactJS with Material-UI

Is there a way to disable the border when clicking a button in ReactJS with Material-UI package? Thank you! Here is an image related to the issue ...

Using curly brackets as function parameters

Can someone help me understand how to pass an emailID as a second parameter in curly braces as a function parameter and then access it in AccountMenuSidebar? I apologize for asking such a basic question, I am new to JavaScript and React. class Invoices ex ...

My JavaScript/jQuery code isn't functioning properly - is there a restriction on the number of api calls that can be made on

Below is the code I have implemented from jquery ui tabs: <script> $(function(){ // Tabs $('#tabs1').tabs(); $('#tabs2').tabs(); $('#tabs3').tabs(); //hover states on the sta ...

Using JSON / jQuery: How to Handle XML Data in the Success Function of an AJAX Post Request

Greetings! I am currently performing an ajax post through a JSP. The JSON data is being sent in string format (parsed using parseJSON, then converted back to a string using JSON stringify). The post operation functions correctly. However, my query lies in ...

Comparing the parsing of fetch() JSON response output in Node.js to parsing a JSON variable

Could someone clarify the difference between parsing a Variable JSON object and parsing fetch() response data JSON object stored in a variable? For example: If we have a variable like this: var myJSON = { "items" : [ { "id" : &q ...

Wrapping a table within an article element

My coding structure appears as follows: <article> <header> <hgroup> <h1>Foo </h1> <h2>Bar</h2> <h3>1337</h3> </hgroup> </header> <table> ...

Error in Vue component when setting the background image URL

Here is my code snippet that sets the background image for a component: style() { return { "background-image": `url(${require(`../../../assets/images/${this .last_result}.png`)})` }; }, The expected URL should be ../../../assets/images/ ...

What is the best way to arrange an array using AngularJs or Javascript?

When a user makes a selection, I want to sort and display an array in alphabetical order. Specifically, when we render data from the backend, I would like to display the fullName in alphabetical order. The $scope.selectedControlOwner is the ng-click event ...

Leverage Input Mask feature in conjunction with Material UI elements

I'm interested in implementing Input Mask with a material-ui component. The packages I am currently using: "react": "^17.0.2" "yup": "^0.32.9" "@mui/material": "^5.0.0" "react-imask": "^6.4.0" One issue I'm facing is that the phone num ...

Creating a series of scalable svgs of uniform size in a row, enabling me to resize them based on width without disrupting the overall design

I need a row of equally sized SVGs with some text below them, like a navigation bar but larger. I almost have it working, but there are some issues with my current setup. To clarify, this is what I am aiming for: The SVGs should be responsive and scale a ...

Updating the Navbar Styles Following User Interactions

My component is functioning well, but I am facing a styling issue. After scrolling, the navbar setState function adds NavbarScroll to the Navbar. How can I style all elements within this component's subtree? I need to make changes to every element an ...

Prevent rendering a file in node.js using ejs if it cannot be found

I have a specific folder structure under the views directory, containing an EJS file named profile_60113.ejs views docs profile_60113.ejs To dynamically render the file based on the groupID (where data.groupID == 60113), I use the following c ...

The design I created includes a horizontal scroll feature and certain elements are not properly aligned in the

Oh man, I'm really frustrated right now. I want all my elements to be centered horizontally on smaller devices, but some of them are slightly off to the side. And to top it off, there's a horizontal scroll appearing - it's like something is ...

What is the reason for JavaScript documentation using a nested array to define a function's parameters in its syntax?

I'm struggling to articulate my question, but as I delve into the documentation for JavaScript and Node.js, I notice they define syntax in a way such as this. var new_array = old_array.concat(value1[, value2[, ...[, valueN]]]) It seems like all th ...

The observable object fails to update the view in Knockout

I'm struggling with this error and need some assistance. I've been working on it for a while, but haven't made any progress. Any help would be greatly appreciated! Thanks! Error: VM4705 knockout-debug.js:3326 Uncaught ReferenceError: Unabl ...

Generate a fresh row in a table with user inputs and save the input values when the "save" button is

HTML: <tbody> <tr id="hiddenRow"> <td> <button id="saveBtn" class="btn btn-success btn-xs">save</button> </td> <td id="firstName"> <input id="first" type="tex ...

To validate any object, ensure that it contains a specific key before retrieving the corresponding value in typescript

When looking at a random object, my goal is to verify that it follows a certain structure. obj = {WHERE:{antherObject},OPTIONS{anotherObject}} Once I confirm the object has the key using hasProperty(key), how can I retrieve the value of the key? I thoug ...

Is there a way to create a scroll down and scroll up button that is located outside of the scroll box

A game designer challenged me to create a custom scrollbar with unique up and down button styles, as well as a custom-looking scrollbar. I wanted to achieve this without using the native browser scrollbar on Windows in Google Chrome. I attempted the follo ...

SVGs are not resizing correctly in Internet Explorer and there is unnecessary blank space around them

Recently, I made the decision to switch to using SVG symbols for one of my projects. However, I encountered a challenge as I needed these SVGs to be responsive. My main objective was to minimize the number of HTTP requests, leading me to explore the option ...