What are the best practices to style the reusable module?

I'm assuming that in a reusable module the user can freely choose the namespace (i.e. can pass anything as an id), so it is impossible to hard code e.g. the CSS. I know how to refer to the id in case of inline CSS or internal stylesheet, like in the example below:

library(shiny)
library(glue)

modUI <- function(id) {
  ns <- NS(id)
  tagList(
  tags$head(tags$style(glue("#{id}-color {{background-color: green;}}"))),
  actionButton(ns("color"), "I'm green")
  )
}

modServer <- function(id) {
  moduleServer(
    id,
    function(input, output, session) {
      
    }
  )
}

ui <- fluidPage(
  modUI("example")
)

server <- function(input, output, session) {
  modServer("example")
}

shinyApp(ui, server)

But let's say that using iternal stylesheet or inline CSS is rather not the best practice to style the whole module and I don't know how to do something similar in the separate .css file.

What would be the best in this case? Perhaps something different than CSS?

id selector is not the only tool available, you can define and add css classes to your ui and style those

1 Like

Edit: I didn't see @nirgrahamuk's comment before posting this - but hopefully the example helps anyway.

I'd recommend working with css classes:

library(shiny)
library(htmltools)

modUI <- function(id) {
  ns <- NS(id)
  tagList(
    actionButton(ns("color"), "I'm green", class = "customcssclass"),
    tagAppendAttributes(wellPanel(p("Test")), class = "customcssclass")
  )
}

modServer <- function(id) {
  moduleServer(
    id,
    function(input, output, session) {}
  )
}

ui <- fluidPage(
  tags$head(tags$style(".customcssclass {background-color: green;}")),
  # alternative - https://shiny.rstudio.com/articles/css.html
  # tags$head(tags$link(rel = "stylesheet", type = "text/css", href = "custom.css")),
  modUI("example")
)

server <- function(input, output, session) {
  modServer("example")
}

shinyApp(ui, server)
1 Like

Yes, indeed, thank you for example. My experience with CSS is very limited.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.