I'm using webpacker with rails 5.1.4 to play with Reactjs, Redux, and react-router-dom.
I have a navbar component that needs to display images, but I'm not able to access images in assets/images
folder and neither in public
folder.
I'm here :
app/javascript/src/components/navbar
My routes defined in main.jsx
:
<BrowserRouter>
<div>
<Alert error={error} />
<Navbar user={user}/>
<Switch>
<Route path="/post/:id" component={PostsShow} />
<Route path="/" component={PostsIndex} />
</Switch>
</div>
</BrowserRouter>
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" />
those 3 attempts were successful once but then it gives me a 404 (Not Found)
because when the path changes, it makes my image path change also. So from root path, I've got my images because /assets/images/logo.png
does exist, but when I'm on /post/:id
, reloading the page or just landing here gives me following 404
:
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 reactjs / rails app?
Thanks
Maybe this helps: https://engineering.klarna.com/migrating-from-rails-asset-pipeline-to-node-s-webpack-684230e3a93a Have a look at the Images part.
Just edit the file
config/webpacker.yml
and replace this line:with this this:
Then, put the image in
app/assets/images
folder and load it like this:You can even create an image folder in your components. Load it in the component file like below-
Webpacker converts these image paths to packs.
For those who may still be having this issue, give this a try:
Put your img in app/assets/images. In this example my image is called 'logo.png'.
In your application.html.erb file, put this in the head:
Now in your component, render the image:
Hope this helps.