Search code examples
ruby-on-railsreactjsreact-routerturbolinks

React with Rails Virtual DOM stacking many nodes


I am using Rails with React and react-router, and I am facing a problem, each time load a view it is stacked in virtual DOM

enter image description here

Here is my application.js (main pack)

document.addEventListener('turbolinks:load', () => {
  const node = document.getElementById('application-content')

  ReactDOM.render(
    <Router>
      <div>
        <Route path="/" exact component={() => require('./main.jsx').default} />
        <Route path="/sign_in" component={() => require('./session.jsx').default} />
        <Route path="/categories" component={() => require('./categories.jsx').default} />
      </div>
    </Router>,
    node
  );

});

Solution

  • When you go to the page html persist but the render of React is called. And inserts another copy of Router. So as an option, you need to move the render to another location.

    This is from turbolinks Readme:

    Navigating with Turbolinks

    Turbolinks intercepts all clicks on links to the same domain. When you click an eligible link, Turbolinks prevents the browser from following it. Instead, Turbolinks changes the browser’s URL using the History API, requests the new page using XMLHttpRequest, and then renders the HTML response.

    During rendering, Turbolinks replaces the current element outright and merges the contents of the element. The JavaScript window and document objects, and the HTML element, persist from one rendering to the next.