Skip to content
Advertisement

Changing Background image using Create React App

Having trouble using Create React App to change a background image I feed to my component through props. The docs say use the import syntax. This works but it would mean I have to hard code every background image to each component. Anyway to do this dynamically?

I noticed it won’t let me use template literals on the import syntax as well. That would have fixed my issue I think.

import '../css/Avatar.css';
import photo from "../images/joe_exotic.jpg";


const Avatar = (props) => {

    return (
        <div 
        style={{backgroundImage: `url("${photo}")`}}
        className="avatar">
        </div>
    )
}

export default Avatar;

P.S: I checked out the other articles on StackOverflow regarding this and they didn’t provide much help.

Advertisement

Answer

If you wanna avoid this way of doing, you can put your images in the public folder of your React app, et grab them like so :

import '../css/Avatar.css';

const Avatar = (props) => {

    return (
        <div 
        style={{backgroundImage: `url("/joe_exotic.jpg")`}}
        className="avatar">
        </div>
    )
}

export default Avatar;
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement