4

I decided to use inline JS styles in React. Everything is ok except images. Here I try to add a background image to div but I get errors.

import React, {Component} from 'react';
import ReactDOM from "react-dom";

var styles = {
color:'violet',
backgroundImage: 'url(' + require('./sun.png') + ')' 
};

class App extends React.Component {
  render() {
    return (
    <div>
        <h1>How to make smth</h1>
        <div style={styles}>test</div>
    </div>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('root'));

I get errors, and I just dont know what loader do i need and how to add it to the webpack config (or package.json)

here is what i get

1 Answer 1

6

Try

import React, {Component} from 'react';
import ReactDOM from "react-dom";
import image from './sun.png';

var styles = {
color:'violet',
backgroundImage: 'url('+image+')'
};

Adding loaders: In the webpack config you are using change

module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015', 'stage-0'],
          plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties'],
        }
      }
    ] 

to

module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015', 'stage-0'],
          plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties'],
        }
      },
      {
        test: /\.png$/,
        loader: "url-loader",
        query: { mimetype: "image/png" }
      }
    ]
Sign up to request clarification or add additional context in comments.

8 Comments

It is looking like a nice solution.I tried but the same error: Module parse failed. .... You may need an appropriate loader to handle this file type. Same error as before
what is the bundler that you are using? Are you using create-react-app? or are you manually configuring the bundler?
I dont use create-react-app here. I use a custom config that I found on codeacademy and modified it little bit github.com/mapledrive/config.git
I tried but the same error. I still need an appropriate loader
try url-loader with {test: /\.(jpg|png|svg)$/, loader: 'url-loader'}
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.