1

I have problems adding a background image to my react (bootstrap) project.

I already found much information about using url/file loaders to load and encode images as base64 strings and then adding them to the style of components.

However, my base64 encoded background image is not showing. Although loaded correctly.

Similar questions on SO (e.g. 0)hinted to encoding error (e.g. saying the string had to be patted. But I don't change the string the loader returns...

Here is the relevant jsx code:

var background = require('url-loader!./../images/bg_1.jpg')

export default class MainView extends React.Component {
  render() {
    var s = {
      backgroundImage: 'url(' + background + ')',
      backgroundSize: "cover",
      backgroundRepeat: "no-repeat",
      width: "600px",
      height: "400px"
    }

    return  (
      <div id="MainView" style={s}>     
      </div>
    );
  }
}

Here is a screenshot of the resulting DOM: DOM

The screenshot shows patterns in the string, which I find suspicious. The base64 string further ends with an '='. Other SO posts (2) suggested that the string should end with an '=='. However this post was years old and about a bug in chrome. I have also tried firefox and adding an '=' to the end but it doesn't do anything in both browsers.

The loader is added in the webpack config as follows:

{
  test: /\.jpg/,
  exclude: /node_modules/,
  loader: "url-loader"
}

Thanks for your help.

krl
  • 5,087
  • 4
  • 36
  • 53
Zapnuk
  • 606
  • 7
  • 15

1 Answers1

0

In the resulting DOM, I can see multiline base64 content.

Make sure that before any newline in the base64 uri, put a backslash \.

You can try any small bas64 uri image as a test or check if background variable has any newline char or not.

Hossam
  • 1,126
  • 8
  • 19
  • I don't think there is a newline in the string. The multilines are just line-breaks from chrome. console.log(background.split("\n").length) returns 1. – Zapnuk Apr 16 '17 at 14:01