The background image is not being properly applied by React's makeStyles

Even after attempting various methods to load the image for the backgroundImage property, it still does not appear on the page. Interestingly, loading external images (such as those from Google) works just fine.

I experimented with the following:

backgroundImage: `url(${Papyrus})`
backgroundImage: "url(" + Papyrus + ")"
backgroundImage: "url(../../assets/images/papyrus.png)"
backgroundImage: Papyrus
backgroundImage: "url(\"../../assets/images/papyrus.png\")"
backgroundImage: "url(assets/images/papyrus.png)"

Despite trying all these approaches, none of them seem to work. The image is being loaded according to the network audit, it can be located in the static folder, but it refuses to display.

App.tsx

import React from 'react';
import makeStyles from './app-styles';
import {Container} from "@material-ui/core";
import Description from "../description/description";

const App: React.FC = () => {
    const classes = makeStyles();
    return (
        <div className="App">
            <Container maxWidth={"xl"}>
                <div className={classes.row}>
                    <Description/>
                </div>
            </Container>
        </div>
    );
};

export default App;

description.tsx

import * as React from "react";
import makeStyles from './description-styles';

interface DescriptionProps {
}

const Description: React.FC<DescriptionProps> = () => {
    const classes = makeStyles();

    return (
        <div className={classes.descriptionCard}>
            <p>Some text</p>
        </div>
    )
};

export default Description;

description-styles.tsx

import makeStyles from "@material-ui/core/styles/makeStyles";
import Papyrus from "../../assets/images/papyrus.png";

export default makeStyles(theme => ({
    descriptionCard: {
        backgroundImage: `url(${Papyrus})`,
        // margin: 'auto',
        height: '25vh',
        width: 'calc(20vw * 0.54 - 2%)',
        borderRadius: 8,
        display: 'flex',
        marginLeft: '10px',
        marginTop: '10px'
    },
    text: {

    }
}))

Answer №1

To make the background image function properly, consider incorporating these extra attributes -

descriptionCard: {
        backgroundImage: `url(${Papyrus})`,
        backgroundPosition: 'center', 
        backgroundSize: 'cover', 
        backgroundRepeat: 'no-repeat',
        // margin: 'auto',
        height: '25vh',
        width: 'calc(20vw * 0.54 - 2%)',
        borderRadius: 8,
        display: 'flex',
        marginLeft: '10px',
        marginTop: '10px'
    }

The reason for including these additional attributes is not entirely clear (perhaps someone could expand on this point), but at times, specific characteristics of the image such as size and position may need to be specified for proper functionality.

Answer №2

Ensure you format it like so:

backgroundImage: `url(images/papyrus.png)` 

It will be effective.

Answer №3

This method is effective for me

    import DesktopImage from "../../assets/desktop.jpg";
    ...

    const customStyle = makeStyles((theme) => ({
        container:{
            backgroundImage: `url(${DesktopImage})`,
            height: '100vh'
        }
    })

It covers the basics. You can further refine the alignment as needed.

Answer №4

If you want to utilize props, give this a shot:

const utilizeStyles = makeStyles({
  background: props => ({
    backgroundImage: \`url(${props.backgroundImage})\`
   })
})

Answer №5

This issue has been causing me trouble since dawn. I finally managed to resolve it. To begin, import the image and incorporate it into the string:

import header_image from "./header_image.png";

imageBackground: `url(${header_image})`

Answer №6

When working with React, one common approach is to import an image and then utilize it as a component.

import myImage from './assets/img/myImage.png'
...
const customStyles = makeStyles({
  root: {
    backgroundImage: `url(${myImage})`,
    minHeight: '100vh', // ensuring height covers entire view
  },
})

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

Component not refreshing when state changes occur

I have a unique react application that resembles the one showcased in this codesandbox link https://codesandbox.io/s/eatery-v1691 By clicking on the Menu located at the bottom center of the page, it triggers the display of the MenuFilter component. The M ...

Develop a Modal Form using Bootstrap (HTML)

I followed a tutorial on creating a modal form with Bootstrap, you can find it here: http://www.youtube.com/watch?v=HCEbp07hfLw I replicated the steps shown in the video, but when I try to open the page in my browser, nothing appears. I have added the Bo ...

Creating Component Variants for Google Optimize A/B testing in Next.js

I've been attempting to create a component variant in Google Optimize beyond just text or color changes, but I haven't found a suitable method to do so yet. I'm looking for guidance on how to integrate/configure Optimize with my code in orde ...

What causes the NavBar to show and hide within a specific range?

Recently, I encountered a perplexing issue with my navbar. It functions correctly except for one strange behavior that has left me baffled. Why does the menu appear when I adjust the width to 631px, but disappear at 600px? And vice versa – why does it wo ...

Contentful does not generate the request

Just embarking on my journey with Contentful and encountering this pesky error. Import error, can't locate file: ./zlib_bindings Haven't made any changes, simply followed the instructions provided in the documentation. The code I've writt ...

Security Error when using the JavaScript map function in FireFox

My current dilemma involves using a JavaScript code to extract the above-the-fold CSS from my websites. Surprisingly, it functions flawlessly on Google Chrome. However, when I attempt to execute it on Firefox, an infamous 'SecurityError' occurs: ...

When trying to import the Editor from draft-js-plugins-editor in a blank project, it results in TypeErrors

I recently started a new React project in Webstorm and added draft-js, draft-js-plugins-editor, draft-js-hashtag-plugin, and draft-js-mathjax-plugin using node modules. Following the instructions provided in the 'getting started' section on thei ...

Customizing the Steps Component in Ant Design

Currently, I am utilizing the Steps component from Ant Design. My goal is to enhance its functionality by adding additional components, like a button placed next to each step's description to make it more interactive. Furthermore, I am looking to inc ...

Every time a row is selected, React and material-ui cause all TableRows to be re-rendered anew

Recently, I came across a code snippet that looks like this: <Table selectable onRowSelection={this.onRecordSelected} bodyStyle={tableBodyStyle}> <TableBody deselectOnClickaway={false} showRowHover displayRowCheckbox={false}> ...

Width of the `div` element is expanding

I'm encountering an issue where a div container is automatically stretching to the full width of the page, instead of adjusting to fit the content within it. Below is the HTML code snippet: <!doctype html> <html> <!-- Head --> <h ...

"Maximizing Space: A Guide to Setting BootStrap Navbar on the Right Side of the Page with Dropdown Width

Take a look at the image below. There is a navbar toggle button on the upper right corner of the page. When I expand it, the dropdown items occupy the entire width of the page, causing an issue where clicking anywhere within the red box triggers the dropdo ...

What is the proper method to restrict a function to execute exclusively on the frontend following authentication on the backend?

My React frontend currently features two buttons—one for authentication and the other for displaying data once authenticated. frontend: const auth = async () => { window.open("callbackApiRouteOnBackend") } const displayData = async () ...

Dropdown element with PrimeNG adorned with a span

I am trying to create a simple form with text inputs and dropdowns. I have successfully implemented the textInput, but I am struggling with the dropdowns. Below is the code that I have so far: <div class="p-grid p-dir-col p-offset-2"> ...

Using the -webkit-box-reflect property along with the CSS position:absolute styling

Running on the Chrome Canary build, I have come across this HTML code snippet: <div id="debug" class="debug" >TEST</div> Additionally, here is the CSS code snippet: -webkit-box-reflect: below 0px -webkit-gradient(linear, ...

ReactJS encountering an invalid dropzone element

Encountering the error "invalid dropzone element". I added var Dropzone = require('react-dropzone'); to my webpack.config.js file in hopes of activating the Dropzone element. This is what is included in my JavaScript file, copied from a Gith ...

One method for deducing types by analyzing the function's return value within a react prop

There is a component definition that accepts two generics: function AsyncFlatList<ApiResponse, Item>({}: { url: string; transformResponse: (response: ApiResponse) => Item[]; keyExtractor: (item: Item) => string; }) { // the implementati ...

How to set the color of the active button within a group of buttons in React using Material UI

I'm having trouble changing the color of a button that is clicked in Material UI. The first button should be active by default. However, I can't use e.target.name because there is no name attribute in the span created within the Button component. ...

Image loading failure detected in ReactJS

In my current project using Reactjs (Nextjs framework), I encountered an issue where I am unable to display an image on a page without specifying the "height" and "width" attributes in the Image tag. I attempted the following code snippet but the image is ...

Locating items within an array of objects using Angular 6 with TypeScript or JavaScript

I have the following code in my HTML template for my Angular 6 application. <div *ngIf ="conversation.participants[conversation.updatedBy.toLowerCase()].firstName">somedata </div> My goal is to search within the participants array object base ...

Is there a way for me to modify this carousel so that it only stops when a user hovers over one of the boxes?

I am currently working to modify some existing code to fit my website concept. One aspect I am struggling with is how to make the 'pause' function activate only when a user hovers over one of the li items, preventing the carousel from looping end ...