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
This is a lesson from The Complete React on Rails Course. Check out the full course and learn how to use React with Rails in a few hours. Rails 5.1 shipped with native support for Webpack and therefore, React, Angular, Vue.js and other libraries, through the webpacker gem.
Now, let’s add React support to our existing Rails app by installing the webpacker gem first. Add the following line to the Gemfile: Then run the webpacker install script: and then run the React install script:
Then run the webpacker install script: and then run the React install script: The installer will add all relevant dependencies using yarn, some changes to configuration files and create a new app/javascript/packs directory from where Webpack will compile any Javascript or CSS, including React components.
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
If we leave resolved_path as [] in webpacker.yml also it works. Example = # Additional paths webpack should lookup modules # ['app/assets', 'engine/foo/app/assets'] resolved_paths: [] static_assets_extensions: - .jpg - .jpeg - .png - .gif - .tiff - .ico - .svg - .eot - .otf - .ttf - .woff - .woff2
You can even create an image folder in your components. Load it in the component file like below-
import React from 'react; import MyImage from '${imagePath}/example1.png' export class MyComponent extends React.Component { render() { return ( <React.Fragment> <img src={MyImage} alt="Image text"/> </React.Fragemnt> ) } }
Webpacker converts these image paths to packs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With