Angelo
Angelo

Reputation: 1765

R shiny datatable - force rows height when a character column contains very long strings

I'm building a Shiny App in R and face the following problem best described by this sample code:

library(shiny)
library(shinydashboard)
library(shinyBS)
library(dplyr)
library(lubridate)
library(DT)

ui <- fluidPage(
  
  mainPanel(
    h3("Table:"),
    dataTableOutput("sample_table1")
  )
  
)

server <- function(input, output, session) {   
  
  output$sample_table1 <- renderDataTable({  #
    df <- head(mtcars, 5)
    
    df$NEW_COL1 <- c("This is an example showing that this row will be displayed with a very wide height because this text is too long",
                     "hello","hello","hello","hello")
    
    df$color <- "blue"
    df$city <- "Kansas"
    df$second_color <- "yellow"
    
    df <- datatable(df,
                    filter = 'top',
                    rownames= FALSE,
                    options = list(scrollX = TRUE
                                   , searching = FALSE
                                   , pageLength = 5
                    )) 
  })
}


cat("\nLaunching   'shinyApp' ....")
shinyApp(ui, server)

if you run this app, you will see that the height of the first row is going crazy because the length of the string in column "NEW_COL1" is way too long. My two questions are:

  1. is there a way to force the height of each row to be 1 (1 meaning like the height of the second row) no matter how long the strings in column NEW_COL1 will be?

  2. in case answer to point 1 is no, I was thinking to simply substring the data in that row. In such case, is it possible to see the full string in each cell by hovering the mouse on the cell of the table?

A somehow related post I found was the following How can I reduce row height in DT datatables but none of the solutions provided there accomplish what I need.

Upvotes: 1

Views: 1282

Answers (1)

HubertL
HubertL

Reputation: 19544

For the second option, you could use code from this question :

    df <- datatable(
        df,
        filter = 'top',
        rownames = FALSE,
        options = list(
            scrollX = TRUE,
            searching = FALSE,
            pageLength = 5,
            columnDefs = list(list(
                targets = "_all",
                render = JS(
                    "function(data, type, row, meta) {",
                    "return type === 'display' && data != null && data.length > 30 ?",
                    "'<span title=\"' + data + '\">' + data.substr(0, 30) + '...</span>' : data;",
                    "}"
                )
            ))
        )
    )

Upvotes: 1

Related Questions