rshinymoduler-mapedit

Dynamically hide module from package in Shiny app


I try to build an application that dynamically shows and hides modules. Following this tutorial and this code, I can show and remove modules built by my own. However, when calling a module from an external package (e.g from mapedit the editModu module) this UI can not be removed through the provided workflow. What is the proper way to remove UI from modules that have been loaded with a package?

So far I used the following code

library(shiny)
library(ggplot2)
library(mapedit)
library(leaflet)

ui <- fluidPage(
  actionButton(
    inputId = "add_module",
    label = "Add a module"
  ),
  actionButton(
    inputId = "remove_module",
    label = "Remove a module"
  ),
  div(
    id = "add_here"
  )
)

server <- function(input, output, session) {
  active_modules <- reactiveVal(value = NULL)
  
  # leaflet blank map for module
    map<-leaflet()%>%
      addProviderTiles(providers$CartoDB.Positron)
    
  observeEvent(input$add_module, {
    current_id <- paste0("id_", input$add_module)
    active_modules(c(current_id, active_modules()))
    
    callModule(editMod, map,id = current_id)
    
    insertUI(
      selector = "#add_here",
      ui = editModUI(id = current_id)
    )
  })
  
  observeEvent(input$remove_module, {
    
    # only remove a module if there is at least one module shown
    if (length(active_modules()) > 0) {
      current_id <- active_modules()[1]
      removeUI(
        selector = paste0("#", current_id)
      )
      
      # update the list of currently shown modules
      active_modules(active_modules()[-1])
    }
  })
}

shinyApp(ui, server)

Solution

  • In the code you provided, the module loaded with "add_module" is not called #id_n, but #id_n-map; you need to change the selector name in removeUI for:

      removeUI(
        selector = paste0("#", current_id, "-map")
      )
    

    You can check the id of any element from your shiny app by right clicking in the browser, selecting "Inspect Element" and looking for the element of interest.