Skip to content Skip to sidebar Skip to footer

How To Use The 'afterColumnResize' Event With 'rhandsontable'?

The JavaScript library Handsontable has an event afterColumnResize, triggered when a column is manually resized. How to use it with the 'rhandsontable' package in Shiny?

Solution 1:

Here is how:

library(shiny)
library(rhandsontable)
library(htmlwidgets)

jsCode <- c(
  "function(el, x) {",
  "  Handsontable.hooks.add('afterColumnResize', function(index, size){",
  "    Shiny.setInputValue('newsize', {index: index+1, size: size});",
  "  });",
  "}"
)

ui <- fluidPage(
  rHandsontableOutput("dataTable"),
  br(),
  verbatimTextOutput("sizeinfo")
)

server <- function(input, output, session) {
  df = data.frame(
    company = c('a', 'b', 'c', 'd'),
    bond    = c(0.2, 1, 0.3, 0),
    equity  = c(0.7, 0, 0.5, 1),
    cash    = c(0.1, 0, 0.2, 0),
    stringsAsFactors = FALSE
  )
  output$dataTable <- renderRHandsontable({
    rhandsontable(df, manualColumnResize = TRUE, manualRowResize = TRUE) %>% 
      onRender(jsCode)
  })
  output$sizeinfo <- renderPrint({
    req(input$newsize)
    sprintf(
      "Column %d has new size %dpx.", 
      input$newsize$index, input$newsize$size
    )
  })
}

shinyApp(ui, server)

enter image description here


Post a Comment for "How To Use The 'afterColumnResize' Event With 'rhandsontable'?"