Marcel
Marcel

Reputation: 1555

Set background in React.js using style

I want to add a background image in React.js by using a style definition, which works:

let imgUrl = 'images/berlin.jpg'    
let styles = {
        root: {
            backgroundImage: 'url(' + imgUrl + ')',
            overflow: 'hidden',
        },
        ...

enter image description here

As you can see, the image repeats in x-direction. So I wanted to extend it by:

let imgUrl = 'images/berlin.jpg'
let styles = {
    root: {
        backgroundImage: 'url(' + imgUrl + ')',
        backgroundImage: {
            flex: 1,
            resizeMode: 'cover', // or 'stretch'
        },
        overflow: 'hidden',
    },
    ...

But the image is not loaded anymore:

enter image description here

So how to set the background image and adjust it in React.js?

Upvotes: 14

Views: 90368

Answers (4)

If you use an image as background, is better to use the 'backgroundImage' property.

If you use the 'background' property, this may cause issues on reloading the component (e.g. 'cover' attribute will not apply properly).

Solution proposed:

let imgUrl = 'images/berlin.jpg'; 

<div className = 'Component-Bg' 
     style = {{ backgroundImage: `url(${imgUrl})`,
                backgroundSize: 'cover', 
                backgroundPosition: 'center center',
                backgroundRepeat: 'no-repeat',
              }}>
</div>

Upvotes: 8

Clarifing another answer

let imgUrl = 'images/berlin.jpg'
let styles = {
    root: {
       backgroundImage: `url(${ imgUrl })`
       backgroundRepeat  : 'no-repeat',
       backgroundPosition: 'center',
  }
}

Upvotes: 14

Marcel
Marcel

Reputation: 1555

This works:

    let imgUrl = 'images/berlin.jpg'
    let styles = {
        root: {
            backgroundImage: 'url(' + imgUrl + ')',
            backgroundSize: 'cover',
            overflow: 'hidden',
        },
        ...

enter image description here

Upvotes: 17

FLCcrakers
FLCcrakers

Reputation: 445

Have you tried somthing like this : 

let imgUrl = 'images/berlin.jpg'
let styles = {
root: {

    background: 'url('+ imgUrl + ') noRepeat center center fixed',
    backgroundSize: 'cover',
}

Inspired from this post: Stretch and scale a CSS image in the background - with CSS only

Upvotes: 4

Related Questions