Web app reactivity in 10 minutes

22.11.2020 by Premysl Donat

So you want to make your server side rendered web app reactive, eh? Want it to feel like native app, no page reloads, "more modern" maybe? Let's see how hard is that.

Installation

Grab and install Turbolinks. Following is an excerpt for install inside Rails app but Turbolinks can enhance any stack. For install in other stacks follow theirs docs.

  1. Add the turbolinks gem, version 5, to your Gemfile: gem 'turbolinks', '~> 5.2.0'
  2. Run bundle install
  3. Add //= require turbolinks to your JavaScript manifest file (usually found at app/assets/javascripts/application.js).

Now there are no visible page reloads and we are only one step away from the full experience, which is to have the browser preserve the same scroll location. Add the following code somewhere after the included Turbolinks:

Turbolinks.scroll = {};

document.addEventListener("turbolinks:load", ()=> {
  const elements = document.querySelectorAll("[data-turbolinks-scroll]");

  elements.forEach(function(element){
    element.addEventListener("click", ()=> {
      Turbolinks.scroll['top'] = document.scrollingElement.scrollTop;
    });

    element.addEventListener("submit", ()=> {
      Turbolinks.scroll['top'] = document.scrollingElement.scrollTop;
    });
  });

  if (Turbolinks.scroll['top']) {
    document.scrollingElement.scrollTo(0, Turbolinks.scroll['top']);
  }

  Turbolinks.scroll = {};
});

Full credit for this snippet goes to Sedad Kosovac. I googled this and didn't change a thing in it. Hell this article is his article only rewritten.

Then on any link or button you want your page to preserve position just add an HTML data attribute `data-turbolinks-scroll = "false"` and that's it. Really, that is all. Look:

reactivity presentation