Search code examples
rshinyshinyappsshiny-reactivityshinywidgets

R Shiny: Conditionally require user to select pickerInput


I have two pickerInput values in the app. In the first, geography, the user can select to view either state (default) or county data. If the user selects county, I'd like to require that they pick a state from the second pickerInput, which is just a list of states. It is not required that the user pick a state when input$geography == "state".

I have considered putting this inside of a modalDialogue but it wasn't working. I also tried an updatePickerInput which didn't work either.

What is the best way of conditionally requiring the user to select a value from a pickerInput?

Thank you.


Solution

  • Here is a solution with shinyjs :

    
    
    library(shiny)
    library(shinyWidgets)
    library(shinyjs)
    
    ui <- fluidPage(
    
      useShinyjs(),
    
      pickerInput("pick_1", choices = c("state","county"), multiple = FALSE, selected = "state"),
      shinyjs::hidden(
        pickerInput("pick_2", choices = state.name, multiple = TRUE)
      )
    
    
    )
    
    server <- function(input, output, session) {
    
      observe({
        toggleElement("pick_2", condition = input$pick_1 == "state")
    
      })
    
    
    }
    
    shinyApp(ui, server)