Search code examples
rshinydt

R shiny datatable pagination and show all rows as options


I have a datatable in a shiny application where I am doing pagination to show only 15 rows. But can I add an option where the user can see 15 rows at a time using pagination or a show all button which will show all the records with a scroll bar may be.

library(shiny)
library(DT)
library(shinyWidgets)
library(shiny)


shinyApp(

  ui = navbarPage(
    title = 'DataTable',
    tabPanel('Display length',     DT::dataTableOutput('ex2'))
  ),

  server = function(input, output, session) {

    output$ex2 <- DT::renderDataTable(
      DT::datatable(
        iris, options = list(
          lengthMenu = list(c(5, 15, -1), c('5', '15', 'All')),
          pageLength = 15
        )
      )
    )

    }
    )

Solution

  • How about this, using the buttons extension. We define a custom button that calls the javascript function page.len(-1), where -1 means all rows:

    shinyApp(
    
      ui = navbarPage(
        title = 'DataTable',
        tabPanel('Display length',     DT::dataTableOutput('ex2'))
      ),
    
      server = function(input, output, session) {
    
        output$ex2 <- DT::renderDataTable(
          DT::datatable(
            iris, 
            extensions = 'Buttons',
            options = list(
              dom = 'Bfrtip',
              lengthMenu = list(c(5, 15, -1), c('5', '15', 'All')),
              pageLength = 15,
              buttons = list(
                list(
                  extend = "collection",
                  text = 'Show All',
                  action = DT::JS("function ( e, dt, node, config ) {
                                        dt.page.len(-1);
                                        dt.ajax.reload();
                                    }")
                )
              )
            )
          )
        )
    
      }
    )