Search code examples
rshinyservermodule

Using insertUI and actionButton Combination in R Shiny Modules


I am trying to use the combination of Action Button and InsertUI to help the user input excel Files. Once the user clicks on the button, the FileInput box should appear (I will then handle the fileinput$datapath later to create a dataframe.)

In the code below, I try to:

  1. generate a button using actionButton in the UI code
  2. Use the actionButton via ObserveEvent to trigger the InsertUI code which should ideally insert the fileInput part of the code once the button in 1. is clicked. I want the file input to be in the server part of the code rather than UI part of the code.
  3. I tried the below code where i can generate a button, but unable to trigger the observeEvent. Any help here is highly appreciated please.
library(shiny)

Import.Excel.Data.UI <- function(id){
  
   ns <- NS(id)
  
  tagList(
    actionButton(ns("AddExcelDataButton"), label = "Click Here to Add Excel Data"),
  
  )
  
}


Import.Excel.Data.Server <- function(id){
  moduleServer(id, function(input, output, session){
    ns <- session$ns
    observeEvent(eventExpr = input$AddExcelDataButton,
                
                 insertUI(selector="#AddExcelDataButton",
                          where = "afterEnd",
                          ui = fileInput(inputId = paste0("File",input$AddExcelDataButton),
                                         label = paste0("Path for File",input$AddExcelDataButton),
                                         multiple  = FALSE)))
    
  })
}


Import.Excel.Data.App <- function(){
  ui <- fluidPage(
   Import.Excel.Data.UI("File1")
  )
  
  server <- function(input, output, session){
    Import.Excel.Data.Server("File1")
  }
  
  shinyApp(ui, server)
}

Import.Excel.Data.App()

Solution

  • You need to use the namespace:

    insertUI(selector=paste0("#", ns("AddExcelDataButton")), ......