Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React & Webpack: Loading and displaying images as background-image

I'm creating a banner-like component with image set as a component's background but I can't get it to work. I tried different suggestions posted online to no luck and at the moment I'm not sure whether my mistake is within react code or it's the webpack that doesn't load the files correctly.

Here's my file structure:

AppFolder
 - client/
 -- components/
 -- data/
 -- images/
 ----- banners/
 ------- frontPageBanner2.png
    ------- 
 -- styles/
 -- myApp.js
 -- store.js
    ---------
 - index.html
 - package.json
 - webpack.config.dev.js

Here's my webpack configuration:

var path = require('path'); 
var webpack = require('webpack');

module.exports = {
  devtool: 'source-map',
  entry: [
    'webpack-hot-middleware/client',
    './client/myApp'
  ],
  output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  module: {
    loaders: [
    // js
    {
      test: /\.js$/,
      exclude: /node_modules/,
      loaders: ['babel'],
      presets: ['es2015', 'react'],
      include: path.join(__dirname, 'client')
    },
    // CSS
    { 
      test: /\.scss$/,
      include: path.join(__dirname, 'client'),
      loader: 'style-loader!css-loader!sass-loader'
    },

    //    PNG
    {
      test: /\.(jpg|png)$/,
      loader: "url-loader?limit=25000",
      //loader: 'file?name=[path][name].[ext]',
      include: path.join(__dirname, 'client')
    },

    // FontAwesome
    { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
    { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
      exclude: path.join(__dirname, 'client/images'),
      loader: "file-loader" },

    // other SVG
    { test: /\.svg$/,
      loader: 'url-loader',
      query: { mimetype: "image/svg+xml" },
      include: path.join(__dirname, 'client/images')
    },

   ]
  }
};

And here's how I'm using it in the app:

export class Banner extends React.Component {
    render() {
        console.log(this.props.banners);
        // = '../images/banners/frontPageBanner.png'
        const bannerImg = this.props.image.backgroundImage;

        var bannerStyle = {
            background: 'url(' + bannerImg + ')',
            backgroundSize: this.props.image.backgroundSize,
            backgroundPosition: this.props.image.backgroundPosition,
        }

        return (
            <section key={this.props.key} className="container hero" style={bannerStyle}>
                <div className="textbox">
                    <h2>{this.props.title}</h2>
                </div>
            </section>
        )
    }
}

Here's resulting html:

<section class="container hero" style="background: url('../images/banners/frontPageBanner2.png') 100% 100% / contain;">
    ...
</section>

but no image is displayed. Also opening the image src link shows just a blank screen. Why? And how can i fix it?

like image 953
spik3s Avatar asked May 23 '16 09:05

spik3s


People also ask

What is React used for?

React is a JavaScript library developed by Facebook which, among other things, was used to build Instagram.com. Its aim is to allow developers to easily create fast user interfaces for websites and applications alike. The main concept of React. js is virtual DOM.

Is React for HTML or js?

To get an overview of what React is, you can write React code directly in HTML. But in order to use React in production, you need npm and Node. js installed.

Is React for frontend?

React is one of the most popular and widely used libraries (it's not a framework) for frontend development. To give you a gentle introduction, React is an open-source JavaScript library used for frontend development, which was developed by Facebook.

Can React be used with Python?

This is because React uses a very different syntax and data structures than Python, which makes it difficult for Python developers to adapt to. In this article, we'll map out a road plan for getting started with React, as well as the core prerequisites for diving into React as a Python developer.


1 Answers

You should pass a var that is the result of requiring the image, when you require it using webpack, it'll generate a base64 inline image, not a relative path.

var DuckImage = require('./Duck.jpg');

var bannerStyle = {
    backgroundImage: 'url(' + DuckImage + ')',
    backgroundSize: this.props.image.backgroundSize,
    backgroundPosition: this.props.image.backgroundPosition,
}
like image 81
Rafael Angeline Avatar answered Sep 21 '22 12:09

Rafael Angeline