Antonio Mendes
Antonio Mendes

Reputation: 103

How to put a button to add fields in Shiny

I'm creating a Shiny application and I need by default to have two fields for uploading files. However, I need to have a button to add more fields (whenever the user clicks this button, another field for uploading files is added) and a reset button (return to the state with only two fields). How do I do this in Shiny?

body <- dashboardBody(
    tabItems(
      tabItem(tabName = "plot"),
      tabItem(tabName = "table",
              box(width = NULL, status = "primary", solidHeader = TRUE, 
                  title="Upload",
                  fileInput("classe1",
                            label="Class 1",
                            multiple = TRUE, accept = c(".jpg", ".jpeg",".png",".tif")),
                  br(),
                  fileInput("classe2",
                            label="Class 2",
                            multiple = TRUE, accept = c(".jpg", ".jpeg",".png",".tif")),
                  br()
              )
      )
)

enter image description here

Upvotes: 0

Views: 32

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388862

Here's one way to do this using combination of renderUI and uiOutput to dynamically show/hide 3rd fileInput.

library(shinydashboard)
library(shiny)

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(),
  dashboardBody(
    fluidRow(column(6, fileInput("classe1",label="Class 1",
              multiple = TRUE, accept = c(".jpg", ".jpeg",".png",".tif"))),
      column(6, actionButton('add', 'Add a new input'))
    ),
      fluidRow(column(6, fileInput("classe2",label="Class 2",multiple = TRUE, 
              accept = c(".jpg", ".jpeg",".png",".tif"))),
            column(6, actionButton('clear', 'Clear')), 
          ),
          br(), 
          uiOutput('new_button')
    )
)

server <- function(input, output) {
  observeEvent(input$add, {
    output$new_button <- renderUI({
      fileInput("classe3",label="Class 3",multiple = TRUE, 
                accept = c(".jpg", ".jpeg",".png",".tif"))
    })
  })
  observeEvent(input$clear, {
    output$new_button <- renderUI({})
  })
}

shinyApp(ui, server)

enter image description here

Upvotes: 1

Related Questions