RStudio Shiny dynamic selectize

2019-05-10 11:31发布

问题:

In my RStudio Shiny, I got my selectInput inside my server.R, and on ui.R I got a tags statement to change the width and height of the select box.

It works when the page is loaded, but it reverts to the default size when I got to the single type. Any ideas how to solve it?

On ui.R

# [...]
  ,div(class="span6"
   ,radioButtons("viz_multiple", "Select Type:",
          c("Select From List (can use Up/Down + Enter)" = "multiple",
            "Search One (Delete then type keyword)"  = "single")
    )
   )
  )
  ,div(class='row-fluid'
  ,div(class='span12', uiOutput("image_list"))
  ,tags$head(tags$style(type="text/css", "select#iimage_list             { width: 1000px; height: 40px; }"))
  )
 # [...]

On server.R

# [...]

output$image_list <- renderUI({
  imagelist = image_ls()
  iimage_list <- as.vector(sort(unique(as.character(imagelist)),decreasing=TRUE))
  length_list = length(iimage_list)
  selectInput("iimage_list",paste0("samples (",length_list,")"),choices=iimage_list, selectize = input$viz_multiple == 'single')
})
# [...]

Any ideas how to apply the tags command also when the user switches from multiple to single?

回答1:

You need to add the css dynamically also. To target the selectize input you need to target select#dataset + .selectize-control rather then select#dataset

library(shiny)

runApp(list(
  ui = bootstrapPage(
    radioButtons("viz_multiple", "Select Type:",
                 c("Select From List (can use Up/Down + Enter)" = "multiple",
                   "Search One (Delete then type keyword)"  = "single")
    )
    , uiOutput("myUI")
  ),
  server = function(input, output){
    output$myUI <- renderUI({
      myCSS <-if(input$viz_multiple == 'single'){
        tags$style(type="text/css", "select#dataset + .selectize-control{ width: 1000px; height: 40px; }")
      }else{
        tags$style(type="text/css", "select#dataset { width: 1000px; height: 40px; }")
      }
      tagList(
        selectInput('dataset', 'Choose Dataset', c('mtcars', 'iris'), selectize = (input$viz_multiple == 'single'))
        , myCSS
      )
    })
  }
))

or have two seperate CSS entries one for the select and one for the selectize:

library(shiny)
runApp(list(
  ui = bootstrapPage(
    radioButtons("viz_multiple", "Select Type:",
                 c("Select From List (can use Up/Down + Enter)" = "multiple",
                   "Search One (Delete then type keyword)"  = "single")
    )
    , uiOutput("myUI")
    , tags$style(type="text/css", "select#dataset + .selectize-control{ width: 1000px; height: 40px; }")
    , tags$style(type="text/css", "select#dataset { width: 1000px; height: 40px; }")
  ),
  server = function(input, output){
    output$myUI <- renderUI({
      selectInput('dataset', 'Choose Dataset', c('mtcars', 'iris'), selectize = (input$viz_multiple == 'single'))
    })
  }
))


标签: r shiny rstudio