rreactable

Make reactable resizeable with minimal witdth of column header


I'm creating a reactable table which is resizeable. The problem is that some column names are longer and are not shown at first because of the table being resizeable. Here is some simple reproducible example:

library(reactable)
data <- aggregate(. ~ Species, iris, toString)

reactable(
  data,
  wrap = FALSE,
  resizable = TRUE,
  bordered = TRUE,
  columns = list(Petal.Length = colDef(name = "Petal Length (cm)"),
                 Sepal.Length = colDef(name = "Sepal Length (cm)"))
)

Created on 2024-12-03 with reprex v2.1.1

enter image description here

As you can see some columns are not shown initially with the minimum width of the column name. So I would like to have a reactable table resizeable, but the minimum column width should be the width of the column header. Does anyone know how to achieve this?


Solution

  • The parameter columns just needs to be given a named list of the correct form. You can build this using R's functional programing tools. I like to use the purrr package. We will automate @zx8754's answer.

    You can observe that

    target <- list(Petal.Length = colDef(name = "Petal Length (cm)",
                                         width = nchar("Petal Length (cm)") * 9),
                   Sepal.Length = colDef(name = "Sepal Length (cm)",
                                      width = nchar("Sepal Length (cm)") * 9))
    

    can be called outside of the reactable and doesn't even need the data.

    my_new_names <- c(Petal.Length = "Petal Length (cm)",
                      Sepal.Length = "Sepal Length (cm)")
    
    one_col <- function(label){
        colDef(name = label, width = nchar(label)*9)
    }
    
    all.equal(target, purrr::map(my_new_names, one_col))
    

    Now we just need to pass this to the reactable:

    reactable(
        data,
        wrap = FALSE,
        resizable = TRUE,
        bordered = TRUE,
        columns = purrr::map(my_new_names, one_col))