Search code examples
rshinyshinywidgets

materialSwitch does not work inside a renderUI


I'd like to use shinyWidgets::materialSwitch instead of a checkbox in my app for an improved UI.

However, I can't seem to get materialSwitch to work when used with renderUI/uiOutput. The input displays properly but doesn't seem to register a click to "switch".

For the purposes of my app - I need this to be inside a renderUI.

Pkg Versions:
shinyWidgets_0.7.2
shiny_1.7.2

library(shiny)
library(shinyWidgets)
# library(shinyjs)

ui <- fluidPage(
  div(class="row",
    column(width = 3,
      uiOutput("switch")
    )
  )
)

server <- function(input, output, session) {
  
 output$switch = renderUI({
   materialSwitch(
    inputId = "switch",
    label = "Show Count",
    right = TRUE,
    status = "primary",
    value = FALSE
   )
 })
}

shinyApp(ui = ui, server = server)

Why is this happening, and how can the problem be fixed?


Solution

  • The issue is that you give same name "switch" to both uiOutput.outputId and materiaSwitch.inputId.

    It works OK when they get different ids:

    library(shiny)
    library(shinyWidgets)
    
    ui <- fluidPage(
      div(class="row",
          column(width = 3,
                 uiOutput("switch"),
                 textOutput("result")
          )
      )
    )
    
    server <- function(input, output, session) {
      
      output$switch = renderUI({
        materialSwitch(
          inputId = "switchButton",
          label = "Show Count",
          right = TRUE,
          status = "primary",
          value = FALSE
        )
      })
      output$result = renderText(input$switchButton)
    }
    
    shinyApp(ui = ui, server = server)