cssrshinyuioutput

Inline uiOutput in R Shiny


I am trying to generate a sequence depending on the selectInputs by users. The problem now is that layout of the sequence is vertical. My question is how to align them horizontally or inline. I tried to set uiOutput as inline=TRUE, but it did not work as expected. A similar question was asked previously on shiny google group with the code (https://groups.google.com/forum/#!searchin/shiny-discuss/inline$20uioutput%7Csort:date/shiny-discuss/WD9jh_mHArM/_bYFR_MVBgAJ), and it used slightly different user interface as add/remove letter in my case.

library(shiny)
sequence <- letters[1:20]

ui <- fluidPage(
  h2("Sequence Length:"),
  fluidRow(column(width=10, numericInput("seqlen", label=NULL, value=10))),

  h2("Sequence:"),
  fluidRow(column(width=10, uiOutput("selects")))

)

server <- function(input, output){

  output$selects <- renderUI({
    len <- as.integer(input$seqlen)
    lapply(1:len, function(i) {
      selectInput(inputId = paste0("letter", i),
                  label = NULL,
                  choices = sequence,
                  width="15%")
    })

  })

}

runApp(list(ui=ui, server=server))

Solution

  • I'd recommend using display: inline-block in CSS to inline divs. Since you can't really customize the outer selectInput div, you could wrap it in a new div like

    library(shiny)
    sequence <- letters[1:20]
    
    ui <- fluidPage(
      h2("Sequence Length:"),
      fluidRow(column(width=10, numericInput("seqlen", label=NULL, value=10))),
    
      h2("Sequence:"),
      fluidRow(column(width=10, uiOutput("selects")))
    )
    
    server <- function(input, output){
    
      output$selects <- renderUI({
        len <- as.integer(input$seqlen)
        lapply(1:len, function(i) {
          div(
            selectInput(
              inputId = paste0("letter", i),
              label = NULL,
              choices = sequence
            ), 
            style = "display: inline-block;"
          )
        })
      })
    }
    
    runApp(list(ui=ui, server=server))
    

    A stylesheet might be better than the inline CSS here, especially if you wanted to customize other properties like margin, width, etc.