Utilizing React JS Styled-Components to Import Images from the Public Directory

I've been attempting to set the image as a background-image from the public folder using styled-components. I've tried the following:

import styled from "styled-components";
import Background from 'process.env.PUBLIC_URL + /images/background.svg'

export const HomeContainer = styled.section`
  height: 100vh;
  max-width: 100vw;
  background-image: url(${Background});
  background-repeat: no-repeat;
  background-size: cover;
`;

and also this:

import styled from "styled-components";

export const HomeContainer = styled.section`
  height: 100vh;
  max-width: 100vw;
  background-image: url('process.env.PUBLIC_URL + /images/background.svg');
  background-repeat: no-repeat;
  background-size: cover;
`;

How can I go about importing it correctly? Thanks in advance

Answer №1

If you want to improve your development process, I highly suggest setting up a jsconfig file with a base path configuration.

{
  "compilerOptions": {
      "jsx": "react",
      "baseUrl": "./",
  }
}

After that, you can easily access your images by using

import img from "public/images/whatever.png

Answer №2

Give this a shot, it's currently functioning well on my end.

import backgroundImage from "../images/background.png";

const Container = styled.div`
  background-image: url(${backgroundImage});
`

Answer №3

I searched online for a solution but came up empty-handed, just like you.

That's when I decided to utilize props:

import styled from "styled-components";

const HomeContainer = styled.section`
  height: 100vh;
  max-width: 100vw;
  background-image: url(${ ({Background}) => Background });
  background-repeat: no-repeat;
  background-size: cover;
`;

const App = () => {
  return (
    <HomeContainer Background={ process.env.PUBLIC_URL + 'where your image at' } />
  )
}

Answer №4

Feel free to utilize this code snippet:

background-image: url(${process.env.PUBLIC_URL}/images/background.svg);

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

Accessing the next and previous elements using jQuery

Aug: <input type="text" value="100000" name="targetMonth_8" id="targetMonth_8" class="targetMonth" disabled> Sep: <input type="text" value="100000" name="targetMonth_9" id="targetMonth_9" class="targetMonth" disabled> Oct: <input type="text" ...

Why do I keep getting an ExpressionChangedAfterItHasBeenChecked error after trying to update a random color in an

Is there a way to assign a random color from an array without causing the error message: "ExpressionChangedAfterItHasBeenChecked"? Even though the color of the chip changes quickly before the message appears, it seems like it's working. How can I reso ...

Ways to stop Bootstrap 4 dropdown from appearing when clicking on an input field?

Here is a straightforward bootstrap dropdown menu example, but with a twist - the toggle element is a text input. Instead of showing the dropdown on click event, I want it to appear when the user inputs something so I can dynamically populate the menu base ...

Remove child elements in Jquery that do not match the specific numbers saved in the array

I've got this array: var numbersArray = [1, 2, 4, 5] and also an unordered list in HTML <ul> <li> item 1 </li> <li> item 2 </li> <li> item 3 </li> <li> item 4 </li> <li> item 5 ...

The Socket.io client establishes connections with multiple servers simultaneously

Imagine this scenario: I am using nodejs and socket.io, and a question comes to mind. What would happen if one client establishes connections with multiple servers like this: socket = io.connect('http://server1') //600k sockets already connecte ...

Having issues with Next.js server-side rendering when integrating API functionality

"Not building properly" means that the project is not fully completing the build process. I've developed a simple blog project with dynamic SSR that pulls data from the Notion-API to generate static blog pages. Everything functions correctly ...

Utilization of z-index with float: left within an image gallery in CSS

Currently, I am working on an image gallery that has content generated randomly. In terms of CSS, the images are positioned using the following code: .item { width: 200px; margin: 10px; float: left; } To add some functionality, I have implemented ...

Mastering intricate string manipulation using JavaScript regular expressions

I have a JavaScript/Node JS program that generates meaningful names according to the following rule: Input: "tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId" Expected output: "TenancyAccountAcco ...

Unchecking and checking the radio button is necessary in order for it to function properly

Today, I'm puzzled by the odd behavior of my radio buttons in a pixel drawer project. In order for the radio button to function properly, I have to uncheck it and then recheck it. The pixel drawer allows me to change colors and sizes using these radio ...

Is it necessary for Webpack to package all dependent node modules with the final bundle in production mode?

It's common knowledge that when we run npm run build, React scripts utilize Webpack to create a bundle by examining the entire dependency graph (following imports) and generating a bundle.js which is then stored in the dist/build folder for production ...

the value of properrty becomes undefined upon loading

In my code, there exists an abstract class named DynamicGridClass, containing an optional property called showGlobalActions?: boolean?. This class serves as the blueprint for another component called MatDynamicGridComponent, which is a child component. Ins ...

When a function is used to set state in the constructor, React may fail to render

I am having trouble initializing the page based on the user's login status. I attempted to set the initial state using a function, but the view is not updating after the API call is completed. Currently, when the code is executed, I see Part 3. im ...

Does React Router load all the routes upfront when in use?

When creating a multi-page React application, my goal is to minimize bandwidth usage. I am wondering if using react-router will result in all pages being loaded at the start or only when they are called upon. ...

Updating NPM packages versions is currently restricted

I'm in the process of creating a Next.JS application using create-next-app. However, I've noticed that in the package.json file it lists the following dependencies: "eslint": "8.43.0", "eslint-config-next": &quo ...

The issue of Vue.js template errors within inline code

I am experimenting with using inline-template in combination with vue.js 2.0. This usage is within the context of Laravel blade 5.4: <users inline-template> <tbody> @foreach($users as $user) <tr> ...

Retrieve information in JSON format from a document

I'm trying to extract data from a JSON file without knowing the exact location of the data. Here is an example JSON: var names= [ { "category":"category1" , "name1":"david", "name2":"jhon", "name3":"peter" }, { "category":"catego ...

Are Firefox and Internet Explorer experiencing issues with CSS rendering accurately?

Experiencing some problems with IE and Firefox CSS To see the issue, visit Check it out in Chrome - it's displaying correctly there But when you view it in IE or Firefox, it's acting strange. Am I making a mistake somewhere? Any help would b ...

Preventing JavaScript from refreshing the page when using location.replace for the second time with the identical URL

I've encountered an issue while using location.replace to reload a page that relies on GET variables for displaying a success message. The problem arises when the URL specified in the location.replace call is identical to the current one, causing the ...

utilize javascript variables within an HTML document

I keep encountering a strange error (Express 400 Error: Bad Request) Some lines are translated to the variable value, while others just output an error. This is an example of my code: exports.add_comment = function(req, res){ var id = req.params.id; ...

React to the Vue: Only activate the event if the key is pressed twice consecutively

In my application, I am creating a unique feature where users can trigger a window to appear by inputting the symbol @ (shift + 50). This will allow them to access predefined variables... <textarea @keyup.shift.50="showWindow"></textarea> My ...