Home > database >  materialSwitch does not work inside a renderUI
materialSwitch does not work inside a renderUI

Time:12-31

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(,
    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?

CodePudding user response:

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(,
      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)

CodePudding user response:

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

  • Related