Search code examples
ruby-on-railswebpacker

When styling Webpacker React components, how to properly define the image url for css properties like backgroundImage?


I'm sure this is a very basic question and that I'm overlooking something obvious. I've only recently started to learn how to use Webpacker and React within Rails.

In a React component, if I'm setting up css theme attributes that use an image, how do you reference that image? e.g.,

const styles = theme => ({
    image: {
        backgroundImage: 'url( ??? )', // what should this path be?
    }
})

I've searched a lot and tried numerous approaches, including:

accessing images from asset pipeline by adding resolved_paths: ['app/assets/images'] to Webpacker.yml.

put images in app/javascript/images, added require.context('../images', true); to application.js and update the theme css backgroundImage: url('../images/my_image.jpg').

put images in app/javascript/packs/images and update the theme css backgroundImage: url('../images/my_image.jpg')

and others.

I'm feeling in the dark here, and not sure if I'm doing this correctly or whether I have other issues that are preventing the images being displayed.


Solution

  • Webpack treats everything as a JavaScript module. When referencing an image from JavaScript within a Webpack-based project, you import it like any other module. The imported variable represents the image's url. For Rails with Webpacker, Webpacker's config will instruct Webpack to emit an imported image as a separate file.

    Here's an example:

    import React from 'react'
    
    import myImage from '../../images/myImage.jpg'
    
    const styles = {
      backgroundImage: `url(${myImage})`,
      // ...
    }
    
    export default function ({ title }) {
      return (
        <div style={styles}>
          Hello {title}!
        </div>
      )
    }
    

    Check out the demo I created here for more context: https://github.com/rossta/rails6-webpacker-demo/compare/example/react-image