Search code examples
rshinyshinyjs

Reset conditionalPanel fileInputs with rshiny and shinyjs()


In my application the user can select a number of sessions, which determines how many files widgets the user has available where they can upload files.

What I would like to happen is that when the user changes the number of sessions - say from 2 to 3, the fileInputs in the conditional panels reset, ready for the user to upload files again. I've been trying to use shinyjs::reset() in combination with observe() to accomplish this, but it doesn't appear to be working, i.e. the files are still there if the user switches from 2 sessions to 3 sessions.

Basic example below:

library(shiny)
library(shinyjs)

ui <- fluidPage(useShinyjs(),
                
                sidebarLayout(sidebarPanel(
                  selectInput(
                    inputId = "numSessions",
                    label = "Number of sessions",
                    choices = c("2 Sessions" = 2,
                                "3 Sessions" = 3)
                  ),
                  
                  div(
                    id = "conditional-inputs",
                    conditionalPanel(
                      "input.numSessions == 2",
                      fileInput("s1file", "Session 1"),
                      fileInput("s2file", "Session 2")
                    ),
                    
                    conditionalPanel(
                      "input.numSessions == 3",
                      fileInput("s1file", "Session 1"),
                      fileInput("s2file", "Session 2"),
                      fileInput("s3file", "Session 3")
                    )
                  )
                ),
                
              
                mainPanel()))


server <- function(input, output) {
  observe({
    if (input$numSessions == 2) {
      reset("conditional-inputs")
    } else if (input$numSessions == 3) {
      reset("conditional-inputs")
    }
  })
}


shinyApp(ui = ui, server = server)


Solution

  • how about this:

    library(shiny)
    
    ui <- fluidPage(
        sidebarLayout(sidebarPanel(
            selectInput(
                inputId = "numSessions",
                label = "Number of sessions",
                choices = c("2 Sessions" = 2,
                            "3 Sessions" = 3)
            ),
            uiOutput("conditional-inputs")
        ),
        mainPanel()
        )
    )
    
    server <- function(input, output) {
        output$`conditional-inputs` <- renderUI({
            ui <- tagList(
                fileInput("s1file", "Session 1"),
                fileInput("s2file", "Session 2")
            )
            if(input$numSessions == 3) ui <- tagList(ui, fileInput("s3file", "Session 3"))
            ui
        })
    }
    
    shinyApp(ui = ui, server = server)
    
    

    We use renderUI to refresh it. No need to use shinyjs or conditional panel. Clean and simple code