Reputation: 717
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)
Upvotes: 4
Views: 6703
Reputation: 5243
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" }
}
]
Upvotes: 6