1

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?

Jamie
  • 1,793
  • 6
  • 16

2 Answers2

2

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)
HubertL
  • 19,246
  • 3
  • 32
  • 51
  • 1
    Awesome, no idea why I didn't attempt that. Side note: I've been following suit with an existing app where the `uiOutput.outputId` is always the same as the `xxx.inputId` and this is the first time it hasn't worked. Wondering why the other approach works for pickerInput etc but not this. hmm – Jamie Dec 31 '22 at 01:46
  • @HubertL. Could you please explain why to do it this way and not the way I posted. Beside the fact that your answer is the correct one. Just want to understand the pro and cons. Many thanks. – TarJae Dec 31 '22 at 08:02
  • 1
    Hello @TarJae, OP asked for a way to use `materialSwitch` within a `renderUI` while in your answer it's on its own. `renderUI` is used to build dynamic UI. – HubertL Jan 02 '23 at 20:01
0

Here is how it should work:

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

ui <- fluidPage(
  div(style = 'position: absolute;left: 50px; top:100px; width:950px;margin:auto',
      materialSwitch(inputId = "switch",
                     label = "Show Count",
                     right = TRUE,
                     status = "primary",
                     value = FALSE)
  )
)

server <- function(input, output, session) {
  
  output$value1 <- renderText({ input$switch })
  
}

shinyApp(ui = ui, server = server)

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66