14

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?

Marcel
  • 1,537
  • 5
  • 19
  • 38
  • 1
    `backgroundImage` is repeated, but object keys cannot repeat. merge the 2. – dandavis Apr 04 '16 at 22:17
  • @dandavis thanks, how can I merge them? Using url: 'xxx' or src: 'xxx'? – Marcel Apr 04 '16 at 22:18
  • maybe the backgroundImage has a url property? not sure of react's mapping, but i know you can't repeat keys. can you use CSS instead? you can template – dandavis Apr 04 '16 at 22:20

4 Answers4

17

This works:

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

enter image description here

Marcel
  • 1,537
  • 5
  • 19
  • 38
12

Clarifing another answer

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

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>
Erik Martín Jordán
  • 4,332
  • 3
  • 26
  • 36
4

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

Community
  • 1
  • 1
FLCcrakers
  • 345
  • 1
  • 4
  • 17