Save what page of a data table I am on into a variable in R shiny

Viewed 104

Let's say that I have a shiny app containing a datatable.

library(shiny)
library(tidyverse)
library(datasets)
library(DT)

data <- as.data.frame(USArrests)
#data<- cbind(state = rownames(data), data)
ui <- fluidPage(
    dataTableOutput("preview")
)

# Define server logic required to draw a histogram
server <- function(input, output) {

    output$preview<- renderDataTable(
        datatable(data, options = list(searching = T, pageLength = 10, lengthMenu = c(5,10,15, 20), scrollY = "600px", scrollX = T ))
    )
    
}

# Run the application 
shinyApp(ui = ui, server = server)

I would like to be able to save what page of the table a user is on in a variable called x. Would there be any way to go about doing this? Any help is greatly appreciated!

1 Answers
library(shiny)
library(DT)

data <- USArrests

callback <- c(
  "Shiny.setInputValue('pageNumber', 1);",
  "table.on('init.dt', function(){",
  "  var pageInfo = table.page.info();",
  "  Shiny.setInputValue('numberOfPages', pageInfo.pages);",
  "});",
  "table.on('page.dt', function(){",
  "  var pageInfo = table.page.info();",
  "  Shiny.setInputValue('pageNumber', pageInfo.page + 1);",
  "  Shiny.setInputValue('numberOfPages', pageInfo.pages);",
  "});",
  "table.on('length.dt', function(){",
  "  var pageInfo = table.page.info();",
  "  Shiny.setInputValue('pageNumber', pageInfo.page + 1);",
  "  Shiny.setInputValue('numberOfPages', pageInfo.pages);",
  "});"
  
)


ui <- fluidPage(
  br(),
  wellPanel(
    textOutput("displayPageNumber")
  ),
  br(),
  DTOutput("preview")
)

server <- function(input, output, session){
  
  output[["preview"]] <- renderDT(
    datatable(
      data, 
      callback = JS(callback),
      options = list(
        searching = TRUE, 
        pageLength = 5, 
        lengthMenu = c(5, 10, 15, 20), 
        #scrollY = "600px", 
        scrollX = TRUE)
    )
  )
  
  output[["displayPageNumber"]] <- renderText({
    paste(
      sprintf("You are currenly viewing page %s.", input[["pageNumber"]]),
      sprintf("There are %s pages in the table.", input[["numberOfPages"]])
    )
  })
  
}

# Run the application 
shinyApp(ui = ui, server = server)

enter image description here

Related