Rails + React App Pages Require Reload To Render React

Viewed 874

I created a new Rails + React app using rails new exampleapp --webpack=react. On my home page, I have a header in html.erb, and some react jsx being rendered using <%= javascript_pack_tag 'reactfilename' %>.

When I click on a link to my home page, such as <li><%= link_to "Home", root_path %></li>, only the header is rendered. It is only till I reload the page that my react component is shown.

I am running both rails s and ./bin/webpack-dev-server to start my application. The same problem is occurring on my Heroku web server. in which I have the following setup:

Procfile: web: bin/rails server -p $PORT -b 0.0.0.0

Procfile.dev: web: ./bin/rails server webpacker: ./bin/webpack-dev-server

Is this the expected behaviour of a React + Rails app, or is there a problem in my configuration?

2 Answers

I believe this issue has something to do with turbolinks background optimization. One workaround is to cause a complete refresh of the page by setting turbolinks to false:

<%= link_to "Home", root_path, data: { turbolinks: false } %>

With newer versions of turbolinks:

<%= link_to "Home", root_path, data: { turbo: false } %>

make sure you are loading you component after turbolink:load event

document.addEventListener('turbolinks:load', () => {
  let container = document.getElementById('react-order')
  if (!container) return

  ReactDOM.render(
    <OrderForm />,
  container)
})
Related