Henok Tesfaye
Henok Tesfaye

Reputation: 9580

Adding background image for a div in React?

render(){
        const { classes } = this.props;
        const { imageDescription } = this.props.imgDesc;
        const { currentIndex } = this.state;

        var fullPath = `../images/Large/${(imageDescription[currentIndex]).imagePath}.jpg`;
        console.log("Fullpath: "+fullPath);

        return (
            <div style={{ 'background-image': "url(" + require(fullPath) + ")" }}>
            </div>

I have a component that returns a div with a background image, but when it starts it shows an error, Cannot find module '../images/Large/homeTecno.jpg'. But when i change the variable fullPath in the require with the output of the console.log statement it works?

Upvotes: 0

Views: 727

Answers (1)

Kishlin
Kishlin

Reputation: 373

This is because require is only used to import javascript entities (classes, objects, functions, ...) but not images. When setting a background image, only a string is expected, not an object. Which is why your second solution works.

Note that you can also define style properties with an object, with the properties written in camelCase.

Given that your image is accessible through yourdomain.com/images/Large/{...}.jpg. You should be fine doing

const path = (imageDescription[currentIndex]).imagePath;
const fullPath = `url(/images/Large/${path}.jpg)`;
return (
    <div style={{ backgroundImage: fullPath }} />
);

Or a bit quicker

const path = (imageDescription[currentIndex]).imagePath;
const backgroundImage = `url(/images/Large/${path}.jpg)`;
return (
    <div style={{ backgroundImage }} />
);

Which works because writing an object as { object } is equivalent to writting { object: object }

Upvotes: 2

Related Questions