Search code examples
rshinyshinyjs

Show text in shiny app when tabpanel is clean and hide it when output is displayed


I have some plots which are displayed once the submit button is clicked but before that, the tab remains clean. I want some text to be displayed there so that the user can see something before hitting the submit button and once when the button is clicked, I want the text to be removed and it must display the plots.


Solution

  • Here is my take on the example shiny app:

    library(shiny)
    library(shinyjs)
    
    # Define UI for application that draws a histogram
    ui <- fluidPage(
        useShinyjs(),
        
        # Application title
        titlePanel("Old Faithful Geyser Data"),
        
        # Sidebar with a slider input for number of bins 
        sidebarLayout(
            sidebarPanel(
                sliderInput("bins",
                            "Number of bins:",
                            min = 1,
                            max = 50,
                            value = 30),
                actionButton("submit", "Show plot")
            ),
            
            # Show a plot of the generated distribution
            mainPanel(
                tabsetPanel(
                    tabPanel(
                        "Plot",
                        uiOutput("help_text"),
                        plotOutput("distPlot")
                    )
                )
            )
        )
    )
    
    # Define server logic required to draw a histogram
    server <- function(input, output) {
        
        output$help_text <- renderUI({
            HTML("<b>Click 'Show plot' to show the plot.</b>")
        })
        
        plot_data <- eventReactive(input$submit, {
            
            hide("help_text")
            
            # generate bins based on input$bins from ui.R
            x    <- faithful[, 2]
            bins <- seq(min(x), max(x), length.out = input$bins + 1)
            
            # draw the histogram with the specified number of bins
            hist(x, breaks = bins, col = 'darkgray', border = 'white')
        })
        
        output$distPlot <- renderPlot({
            plot_data()
        })
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server)