Search code examples
rshiny

Generating input in the server side of Shiny


I'm trying to generate some new Inputs in a Shiny app after I hit a actionButton but I can see what I'm doing wrong.

histogramUI <- function(id) {
  tagList(

      actionButton(NS(id, "generate_pickers"), "Generate pickers"),
      renderUI(NS(id, "new_button"))
  )
}

histogramServer <- function(id) {
  moduleServer(id, function(input, output, session) {
    
    
    observeEvent(input$generate_pickers, {
      
      new_button <- pickerInput(NS(id, "new_button"), "New Button", choices = c())
      output$new_button <- renderUI(tagList(new_button))
      
    })

  })
}

histogramApp <- function() {
  ui <- fluidPage(
    histogramUI("hist1")
  )
  server <- function(input, output, session) {
    histogramServer("hist1")
  }
  shinyApp(ui, server)  
}

histogramApp()

Solution

  • In the UI you need to use uiOutput instead of renderUI

    uiOutput(NS(id, "new_button"))
    

    Complete code :

    library(shiny)
    library(shinyWidgets)
    
    histogramUI <- function(id) {
      tagList(
        
        actionButton(NS(id, "generate_pickers"), "Generate pickers"),
        uiOutput(NS(id, "new_button"))
      )
    }
    
    histogramServer <- function(id) {
      moduleServer(id, function(input, output, session) {
        
        
        observeEvent(input$generate_pickers, {
          
          new_button <- pickerInput(NS(id, "new_button"), "New Button", choices = c())
          output$new_button <- renderUI(tagList(new_button))
          
        })
        
      })
    }
    
    histogramApp <- function() {
      ui <- fluidPage(
        histogramUI("hist1")
      )
      server <- function(input, output, session) {
        histogramServer("hist1")
      }
      shinyApp(ui, server)  
    }
    
    histogramApp()