Skip to content
Advertisement

background image not showing in React

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 is how I wrote the code. But the picture not working. Screenshot(Failed to compile)

Images are not displayed, how can I display images? Please help me.

Advertisement

Answer

You shouldn’t keep your images in the public folder. When using css inside the src folder you should use the relative path to the image file and during build react manages and updates the paths to their public build one.

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

If you want to keep your image inside public, you can try using ‘../../../../Public/images/img-2.jpg’ as the path, altough it is recommended to keep your images inside src and let react manage them during compile.

Advertisement