Home > Back-end >  conditionalPanel based on values of tabPanel using moduleServer()
conditionalPanel based on values of tabPanel using moduleServer()

Time:02-23

I am trying to use modules while developing a shinyApp and I am failing to add a sidebarPanel that change when I change a tabPanel in the mainPanel. For example, when the user is on "Tab1" a h4() element should be added to the sidebarPanel with "Title" and when the user is on "Tab2" the sidebarPanel should show a selectInput(). This is the code I am using. Any idea on what I am doing wrong?

library(shiny)
# Module UI ####
modUI = function(id) {
  ns = NS(id)
  tabPanel("Dummy Panel",
           sidebarPanel("SibeBarPanel",
                        conditionalPanel("input.ns(mainpanel) == 1", 
                                         h4("Title")),
                        conditionalPanel("input.ns(mainpanel) == 2",
                                         selectInput(ns("s_1"), "Label1", choices = c("A","B")))
           ),
           
           mainPanel(
             tabsetPanel(id=ns("mainpanel"),
                         tabPanel("Tab1", value = 1),
                         tabPanel("Tab2", value = 2))))
}

# Module Server ####
modServer <- function(id) {
  moduleServer(id, function(input, output, session) {
    
  })
}

server = function(input, output, session) {
  modServer("v1")
}


ui = shinyUI(
  navbarPage("Dummy", 
             navbarMenu("This", 
                        modUI("v1")))
)

server = function(input, output, session) {
  modServer("v1")
}

shinyApp(ui, server)

CodePudding user response:

By now conditionalPanel has a ns argument:

The namespace() object of the current module, if any.

Please check the following:

library(shiny)
# Module UI ####
modUI = function(id) {
  ns = NS(id)
  tabPanel("Dummy Panel",
           sidebarPanel("SibeBarPanel",
                        conditionalPanel("input.mainpanel == 1", 
                                         h4("Title"), ns = ns),
                        conditionalPanel("input.mainpanel == 2",
                                         selectInput(ns("s_1"), "Label1", choices = c("A","B")), ns = ns)
           ),
           
           mainPanel(
             tabsetPanel(id=ns("mainpanel"),
                         tabPanel("Tab1", value = 1),
                         tabPanel("Tab2", value = 2))))
}

# Module Server ####
modServer <- function(id) {
  moduleServer(id, function(input, output, session) {
    
  })
}

server = function(input, output, session) {
  modServer("v1")
}


ui = shinyUI(
  navbarPage("Dummy", 
             navbarMenu("This", 
                        modUI("v1")))
)

server = function(input, output, session) {
  modServer("v1")
}

shinyApp(ui, server)

Result:

    <div data-display-if="input.mainpanel == 1" data-ns-prefix="v1-">
      <h4>Title</h4>
    </div>
  • Related