rshinyheaderdt

Column headers not aligning with rest of the table


Considering the R Shiny code below:

library(shiny)
library(DT)

# Define the user interface (UI)
ui <- fluidPage(
  titlePanel("test"),
  
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Choose File 1", accept = ".csv"),
      fileInput("file2", "Choose File 2", accept = ".csv")
    ),
    
    mainPanel(
      tabsetPanel(
        tabPanel("Table 1", DT::dataTableOutput("table1")),
        tabPanel("Table 2", DT::dataTableOutput("table2"))
      )
    )
  )
)

# Define the server logic
server <- function(input, output) {
  
  # Reactive expression to read the first CSV file
  data1 <- reactive({
    req(input$file1)
    read.csv(input$file1$datapath)
  })
  
  # Reactive expression to read the second CSV file
  data2 <- reactive({
    req(input$file2)
    read.csv(input$file2$datapath)
  })
  
  # Render the first CSV file table
  output$table1 <- renderDataTable({
    data1()
  }, rownames = FALSE, options = list(scrollX = TRUE,
                                      autoWidth = TRUE,
                                      columnDefs = list(list(width = 'auto', targets = "_all")))
  )
  
  # Render the second CSV file table
  output$table2 <- renderDataTable({
    data2()
  }, rownames = FALSE, options = list(scrollX = TRUE,
                                      autoWidth = TRUE,
                                      columnDefs = list(list(width = 'auto', targets = "_all")))
  )
}

# Run the Shiny app
shinyApp(ui = ui, server = server)

Once I load a file to the app, the displayed table has a misalignment between the header(s) and the rest of the table. How can I fix that?

Interestingly, this is "fixed" if I change tab, and then click back on the tab with the issue.

Just after loading the file: enter image description here

After clicking on Table 2 tab, and the back to Table 1 tab: enter image description here


Solution

  • You can create a container with centered contents, in particular the table header shall be centered. Therefore you can e.g. replace tabPanel("Table 1", DT::dataTableOutput("table1")) with

    tabPanel("Table 1",
             fluidRow(column(
               align = "center",
               width = 12,
               DT::dataTableOutput("table1")
             )))
    

    and then it will look properly:

    enter image description here