Search code examples
cssreactjstypescriptmaterial-uicreate-react-app

React makeStyles doesn't set background image


Despite trying several ways to load the image for the backgroundImage property, it never shows up in page. Loading external images (for example from google) works as expected.

I tried:

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)"

NONE of them work. The image is loaded when I look at my network audit, I can find it in the static folder, but it's never displayed.

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: {

    }
}))

Solution

  • Add some additional properties to the background image and it will work -

    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'
        }
    

    I'm not sure why we need these additional properties (maybe someone could add to the answer), but sometimes the image needs certain behaviour to be defined, like size, position, etc.