Backgroundimage is not working in react
Asked Answered
P

7

25

I am new to react and trying to get background image with inline styling. But it's not working.

Showing error "url is not defined"

  render() {
    return (
        <div className="phase1" 
             style ={ { backgroundImage: url('https://lh3.googleusercontent.com/MOf9Kxxkj7GvyZlTZOnUzuYv0JAweEhlxJX6gslQvbvlhLK5_bSTK6duxY2xfbBsj43H=w300') } }>

            <input id="search" 
                   type="text" 
                   placeholder={this.state.search} 
                   onChange={this.updateSearch.bind(this)}/>
            &nbsp; &nbsp;&nbsp; &nbsp;

            <Link className="button1" to="Form"> + </Link>
        </div>
       )
    }
 }
Projection answered 5/8, 2016 at 16:41 Comment(2)
wrap it in quotes, you're in JS context when you put curlies in JSX so you're literally trying to call a function called url which doesn't existBerenice
can you show by doing howProjection
U
35

CSS values are always strings. Wrap the backgroundImage value in quotation marks to make it a string:

<div className="phase1" style ={ { backgroundImage: "url('https://lh3.googleusercontent.com/MOf9Kxxkj7GvyZlTZOnUzuYv0JAweEhlxJX6gslQvbvlhLK5_bSTK6duxY2xfbBsj43H=w300')" } }>
Uranie answered 5/8, 2016 at 16:55 Comment(2)
@TheViralGriffin Can you open a new question for the issue you're seeing and paste the code you are using?Uranie
The issue i was facing was minor mistype. Fixed it, thanks.Diaz
E
31

Faced a similar problem and this did the trick for me

style={{backgroundImage: 'url(' + require('./images/sword.png') + ')'}}

the trick was adding the require

Electroballistics answered 11/11, 2017 at 12:35 Comment(2)
Thanks. I have to note here that although I tried many things, this here worked. +1Tactic
Alternatively, ES6 import statement can also be used.Agamic
C
18

In my case, i have url with space on it, so it needs to be wrapped with quotes mark ex: 'url', because i got url (imagePath) directly from server.

<div style={{ backgroundImage: `url('${imagePath}')` }} />

Hope this helps someone.

Ceramist answered 26/2, 2020 at 12:2 Comment(2)
It saved my day! thank you! The ` ' " are so confusing 😂Odontoid
' - This quote inside parenthesis was very important. Thanks!Inflect
A
10

In React putting relative paths for images like this

<div className="container-login100" style={{ backgroundImage: "url('./folder/images/bg-01.jpg')" }}>

doesn't seems to work as it is JSX, you need to import the image or require it

import BackgroundImage from './../frontend_authentication_copied/images/bg-01.jpg'

...

styles = {
        backgroundImage: `url(${BackgroundImage})`
    }

...

<div className="container-login100" style={this.styles}>

Just make sure you put all the images inside the src folder since relative imports are not supported from outside the src folder if create-react-app is used.

Agamic answered 27/9, 2019 at 7:1 Comment(1)
your solution set me free from a problem that I got stuck on for 2 days!Afterdinner
S
5

I've stumbled upon this thread today. I was in need to change the backgroundImage property dynamically, so require was not an option. In my ElectronJS app all I did was:

const imageFilePath = './some/dynamic/path/here';
const style = { backgroundImage: `url('file://${imageFilePath}')` };

Hope this helps somebody :)

Samiel answered 9/8, 2018 at 12:20 Comment(0)
A
4

I was battling with this same issue this morning but i was able to fix it with below snippet.

<div
    className="col-md-4 col-xs-12"
    style={{
      backgroundImage: `url(${require('./path/img.png')})`,
      backgroundPosition: 'center',
      backgroundSize: 'cover',
      backgroundRepeat: 'no-repeat',
    }}
></div>
Arv answered 14/5, 2019 at 15:21 Comment(1)
I'm glad it's helps. Cheers!Arv
S
4

I'm not sure why, but for me only one way that works is like this:

<div style={{backgroundImage: `url(${require("./images/your_image").default})`}}></div>

Without the .default no error would occur, but the image simply would not appear in the html. I hope I helped someone ;)

Squishy answered 23/6, 2021 at 2:52 Comment(1)
Hi Saulo Felipe. The reason you needed .default is because require() imports CommonJS modules and your file/image loader (probably a webpack plugin) exposed the image as an ESM style default export. This only applies to images loaded locally, not from external URLs like in this question. it is hopefully still useful for people coming here with that problem.Donte

© 2022 - 2024 — McMap. All rights reserved.