简体   繁体   中英

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?

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)

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)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM