rshinygolem

conditionPanel does not take into account the conditions


I have two radio buttons A and B. When button A is checked, two widgets are displayed. When we check button B, the widgets of button A are deleted and we display the widgets of button B, same thing if we check button A again. To achieve this I used the function conditionalPanel() but the problem is that all are displayed at the same time. There are button A and button B elements

mod_models_ui <- function(id){ns <- NS(id); tagList(
    radioButtons(ns("radioBtn"), "", c("A" = "idA", "B" = "idB"), selected = "idA"),
    conditionalPanel(
      condition = paste0("input.", ns("radioBtn"), " == 'idA'"),
      h3("A"), textInput("text1", "Widget 1"), textInput("text2", "Widget 2")),
    conditionalPanel(
      condition = paste0("input.", ns("radioBtn"), " == 'idB'"),
      h3("B"),textInput("text3", "Widget 3"),textInput("text4", "Widget 4")))
}

mod_models_server <- function(id){moduleServer( id, function(input, output, session){ns <- session$ns
    observe({print(input$radioBtn) })}

app_ui.R

app_ui <- function(request) {
  tagList(
    ...
    mod_models_ui("radioBtn"))}

app_server.R

app_server <- function(input, output, session) {
  mod_models_server("radioBtn")}

Solution

  • The issue is that similar to accessing elements in R via $ you can access object properties in JS using dot notation (.) only when they are valid variable names, which radioBtn-radioBtn is not, i.e. you have to use bracket notation ([]), e.g. condition = paste0("input['", ns("radioBtn"), "'] === 'idA'"). However, you can achieve your result more easily by using the ns= argument of conditionalPanel:

    mod_models_ui <- function(id) {
      ns <- NS(id)
      tagList(
        radioButtons(ns("radioBtn"), "", c("A" = "idA", "B" = "idB"), selected = "idA"),
        conditionalPanel(
          condition = "input.radioBtn === 'idA'",
          h3("A"),
          textInput("text1", "Widget 1"),
          textInput("text2", "Widget 2"),
          ns = ns
        ),
        conditionalPanel(
          condition = "input.radioBtn === 'idB'",
          h3("B"),
          textInput("text3", "Widget 3"), textInput("text4", "Widget 4"),
          ns = ns
        )
      )
    }
    
    mod_models_server <- function(id) {
      moduleServer(id, function(input, output, session) {
        ns <- session$ns
        observe({
          print(input$radioBtn)
        })
      })
    }
    
    library(shiny)
    
    ui <- fluidPage(
      mod_models_ui("radioBtn")
    )
    
    server <- function(input, output, session) {
      mod_models_server("radioBtn")
    }
    
    shinyApp(ui, server)
    #> 
    #> Listening on http://127.0.0.1:8788
    #> [1] "idA"