Search code examples
rshinytogglehide

Shiny withSpinner hide or toggle


I am trying to hide the spinner at the beginning when no choice has been made yet. This is a simple example of what I have achieved so far.

library(shinycssloaders)

ui <- fluidPage(
  selectInput(inputId = "something",
            label = "Select something:",
            choices = c('','None', 'All', 'Some'),
            selected = ''),
  withSpinner(textOutput(outputId = "text")  )
)

server <- function(input, output) {
  observe({
    toggle(id = 'text', condition = F)

    if(nchar(input$something) > 0 ){
      toggle(id = 'text', condition = T)
      Sys.sleep(1)
      output$text <- renderText(paste("You chose ",input$something))
    }
  })
}

shinyApp(ui,server)

The spinners appear correctly when the choice is changed. Unfortunately, at the beginning the toggle seems to work only on the text, not on the spinner itself. I also tried with withSpinner(textOutput(outputId = "text") , id = 'myspin' ) in the UI and toggle(id = 'myspin', condition = F) in the server, but no luck yet. hide(id = 'text') seems to have no effect either.


Solution

  • You can hide the container at the start and then enable it again

    library(shinycssloaders)
    library(shiny)
    library(shinyjs)
    ui <- fluidPage(
        useShinyjs(),
        selectInput(inputId = "something",
                    label = "Select something:",
                    choices = c('','None', 'All', 'Some'),
                    selected = ''),
        hidden(div(id = 'test', withSpinner(textOutput(outputId = "text"))))
    )
    
    server <- function(input, output) {
        
        observe({
            toggle(id = 'text', condition = FALSE)
            
            if(nchar(input$something) > 0 ){
                show('test')
                toggle(id = 'text', condition = TRUE)
                Sys.sleep(1)
                output$text <- renderText(paste("You chose ", input$something))
            }
        })
    }
    
    shinyApp(ui, server)