Jorge Hernández
Jorge Hernández

Reputation: 662

How I can center the header columns on reactable (r-package)?

Hi and thanks for reading me

I am working on some tables with the "reactable" package in r, but I would like to center only the headings of each column. For example:

library(reactable)
reactable(iris,
          defaultColDef = colDef(
            header = function(value) gsub(".", " ", value, fixed = TRUE),
            cell = function(value) format(value, nsmall = 1),
            align = "center",
            minWidth = 70,
            headerStyle = list(background = "#12a09a")
          ))

Apparently the option colDef(align = "center") centers the entire column, but is there an option to only center the title?

Upvotes: 4

Views: 2703

Answers (1)

JavRoNu
JavRoNu

Reputation: 368

i assume that you are using this tables in an R markdown document or a shiny app. In both you can override the css in order to left align the table text or let the default table and center the title.

In the first case you just need to add this line .rt-align-center{text-align: left;}.

In shiny you just need to add that to your custom css or use the style tag to add it inline like the example below:

library(shiny)
library(reactable)


ui <- fluidPage(
    # inline style tag to define table row text alignment
    tags$style(HTML(".rt-align-center {text-align: left;}")),

    titlePanel("Iris react table"),

    sidebarLayout(
        sidebarPanel(
           helpText("Nothing to see here")
        ),
        mainPanel(
            reactableOutput("table")
        )

    )
)

server <- function(input, output) {

    output$table <- renderReactable({
    
        reactable(iris,
                  defaultColDef = colDef(
                      header = function(value) gsub(".", " ", value, fixed = TRUE),
                      cell = function(value) format(value, nsmall = 1),
                      align = "center",
                      minWidth = 70,
                      headerStyle = list(background = "#12a09a")
                  ))
    })
}

shinyApp(ui = ui, server = server)

If you are working with an Rmarkdown document just add it to the html in the style tag like this:

<style> .rt-align-center {text-align: left;} </style>

and the result:

The desired table

Upvotes: 3

Related Questions