Search code examples
ruby-on-railsreactjswebpackwebpacker

How to handle images in a Rails / Webpacker / React app?


I am using Webpacker with rails 5.1.4 to play with React, Redux, and react-router-dom.

I have a Navbar.jsx component in app/javascript/src/components/ that needs to display an image, but I am not able to access my images stored in app/assets/images/.

Here is what I've tried :

<img src="logo.png" alt="Logo" />
<img src="assets/logo.png" alt="Logo" />
<img src="assets/images/logo.png" alt="Logo" />

From root path the last attempt works because /assets/images/logo.png does exist, but when I navigate to /posts/:id, it gives me the following error:

logo.png:1 GET http://localhost:3000/posts/assets/images/logo.png 404 (Not Found)

Can you help me? And more over what's your way to handle images in that kind or hybrid React/Rails app?

Thanks


Solution

  • Just edit the file config/webpacker.yml and replace this line:

    resolved_paths: []
    

    with this this:

    resolved_paths: ['app/assets']
    

    Then, put the image in app/assets/images folder and load it like this:

    import React from 'react'
    import MyImage from 'images/my_image.svg'
    
    const MyComponent = props => <img src={MyImage} />
    
    export default MyComponent