Site icon R-bloggers

Infinite Scrolling in R Shiny

[This article was first published on Tag: r - Appsilon | Enterprise R Shiny Dashboards, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

As a software engineer whenever I see something interesting in a web application I try to think about the way it was implemented. One of the things that caught my attention was the infinite scrolling functionality on sites like Facebook or Twitter.

Whenever you scroll to the end of the current content, a new batch of content will be loaded allowing you to continuously explore available content.

As I explored how infinite scrolling is implemented I thought what better way to synthesize this knowledge than trying to implement that in R/Shiny?


Why use Infinite Scroll vs Pagination?

Infinite scrolling allows you to display chunks of content to users in a performant manner. A different way of achieving this is the use of pagination. However, even though they achieve similar performance goals, the way users interact with them is different. 

Shiny application layouts are changing. Explore the past and see what’s new in Shiny web app layouts.

With infinite scrolling, the motion of scrolling leads to a new batch of data being shown on the page whenever the user reaches the end of the currently displayed content. In the case of pagination, the user can always see how many pages of data they can explore and they can select a specific page of data to be displayed.

The Pagination vs Infinite Scroll summarizes well the differences between those approaches and highlights their particular advantages. For example, infinite scrolling is easier to use on mobile devices and requires fewer “clicks” compared to pagination. As a result, it might increase user engagement on your page as viewers stay on your website longer; continuously searching for relevant content when they have no particular goal in mind.

How to add Infinite Scroll to your app

With the tooling available today we can implement infinite scrolling in a Shiny app with only a couple lines of JavaScript code.

What is Infinite Scroll in Shiny based on?

The Intersection Observer API is a Web API supported by most modern browsers – it allows you to observe changes in the intersection of a target element with the browser’s viewport (you can think of it as the browser window).

Is your dashboard getting slow? Try R Shiny caching options to increase the speed and responsiveness of your dashboard.

How to set up Infinite Scroll in Shiny?

For the purpose of the post let’s assume a simple example: we want to show an infinite list of randomly generated numbers.

library(shiny)

generate_random_numbers_divs <- function(n) {
  lapply(seq_len(n), function(i) div(runif(1)))
}

ui <- fluidPage(
 generate_random_numbers_divs(100)
)

server <- function(input, output, session) {
}

shinyApp(ui, server)

Now, let’s set up our Intersection Observer. To do that we will also need to add a div that will be placed at the end of the list of our numbers. We will use it to detect the moment users reach the end of the list:

library(shiny)

generate_random_numbers_divs <- function(n) {
  lapply(seq_len(n), function(i) div(runif(1)))
}


ui <- fluidPage( tags$head( tags$script(HTML(' $(document).ready(function() { const observer = new IntersectionObserver(function(entries) { if (entries[0].intersectionRatio > 0) {
            alert("Reached end of list!")
          }
        });

        observer.observe(document.querySelector("#end"));
      })
    '))
  ),
  generate_random_numbers_divs(100),
  div(id = "end")
)

server <- function(input, output, session) {
}

shinyApp(ui, server)

Now, if you run the app and scroll to the end of the list you will see an alert popup:

< !--[if lt IE 9]>< ![endif]--> < video class="wp-video-shortcode" id="video-16784-1" width="450" loop="1" autoplay="1" preload="metadata" controls="controls">< source type="video/mp4" src="https://wordpress.appsilon.com/wp-content/uploads/2022/11/infinite_scroll_alert_rshiny.mp4?_=1" />https://wordpress.appsilon.com/wp-content/uploads/2022/11/infinite_scroll_alert_rshiny.mp4

We are now able to detect when a user reaches the end of the list. The next step is to inform Shiny about it and react appropriately by loading additional random numbers:

library(shiny)

generate_random_numbers_divs <- function(n) {
  lapply(seq_len(n), function(i) div(runif(1)))
}


ui <- fluidPage( tags$head( tags$script(HTML(' $(document).ready(function() { const observer = new IntersectionObserver(function(entries) { if (entries[0].intersectionRatio > 0) {
            Shiny.setInputValue("list_end_reached", true, { priority: "event" });
          }
        });

        observer.observe(document.querySelector("#end"));
      })
    '))
  ),
  generate_random_numbers_divs(100),
  div(id = "end")
)

server <- function(input, output, session) {
  observeEvent(input$list_end_reached, {
    random_numbers_items_batch <- generate_random_numbers_divs(100)
    insertUI(
      selector = "#end",
      where = "beforeBegin",
      ui = random_numbers_items_batch
    )
  })
}

shinyApp(ui, server)

And we are done! We have an app that will infinitely generate new batches of random numbers as the user scrolls.

To add new items to the UI we make use of the insertUI function and define that the new content should be inserted before our #end div begins.

< video class="wp-video-shortcode" id="video-16784-2" width="450" loop="1" autoplay="1" preload="metadata" controls="controls">< source type="video/mp4" src="https://wordpress.appsilon.com/wp-content/uploads/2022/11/infinite_scroll_rshiny_final.mp4?_=2" />https://wordpress.appsilon.com/wp-content/uploads/2022/11/infinite_scroll_rshiny_final.mp4

Example of Infinite Scroll in Shiny

In this post, we described how to implement infinite scrolling in a Shiny app. However, our example is a bit raw and could use some improvements in terms of styling. For example, you could add a loader informing the user that a new batch of content is being generated.

There’s a lot you can do with Shiny. Download a free Shiny template to get started and browse our open-source packages to level up your Shiny project.

You can find a more advanced example on my github [live app], where you can scroll through the universe of Rick and Morty characters (powered by the Rick and Morty API).

< video class="wp-video-shortcode" id="video-16784-3" width="450" loop="1" autoplay="1" preload="metadata" controls="controls">< source type="video/mp4" src="https://wordpress.appsilon.com/wp-content/uploads/2022/11/Rick-and-Morty-Infinite-Scroll-in-R-Shiny.mp4?_=3" />https://wordpress.appsilon.com/wp-content/uploads/2022/11/Rick-and-Morty-Infinite-Scroll-in-R-Shiny.mp4

If you find the Shiny Infinite Scroll helpful, please be sure to give it a star on GitHub. And if you come up with an interesting use, be sure to share it with us at Appsilon. We love to see the community’s creative applications!

Ready to scale your Shiny app? Watch Pedro Silva’s workshop on how to scale Shiny and infrastructure.

The post Infinite Scrolling in R Shiny appeared first on Appsilon | Enterprise R Shiny Dashboards.

To leave a comment for the author, please follow the link and comment on their blog: Tag: r - Appsilon | Enterprise R Shiny Dashboards.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.