Search code examples
rshinyshinyjsshinywidgets

Remove/hide or update a Bootstrap panel from shinyWidget


In order to make an app where panels are created dynamically, I would like to remove, hide and/or update panels from the package shinyWidgets.

I didn't find any function to do so nor way to add IDs to these panel.

If you have the solution or a way around, I would be more than happy. Thank you in advance !

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
    panel(
      heading = "Test panel",
      actionButton("remove_panel", "Remove this panel")
    )
)

server <- function(input, output) {

    observeEvent(input$remove_panel,{
      print("remove panel")
    })
}

shinyApp(ui = ui, server = server)

Solution

  • There is no official method you can use to change the panel states, but we can do it with custom expressions.

    library(shiny)
    library(shinyWidgets)
    library(shinyjs)
    
    ui <- fluidPage(
        useShinyjs(),
        panel(
            heading = "Test panel1",
            id = "test_panel1",
            actionButton("remove_panel", "Remove this panel")
        ),
        panel(
            heading = "Test panel2",
            id = "test_panel2",
           "some content"
        ),
        actionButton("hide_panel", "Hide this panel")
    )
    
    server <- function(input, output) {
        
        observeEvent(input$remove_panel,{
            removeUI('.panel:has([id="test_panel1"])', immediate = TRUE)
        })
        observeEvent(input$hide_panel,{
            toggle(selector = '.panel:has([id="test_panel2"])')
            if(input$hide_panel %% 2 == 1) return(updateActionButton(inputId = "hide_panel", label = "Show this panel"))
            updateActionButton(inputId = "hide_panel", label = "Hide this panel")
        })
    }
    
    shinyApp(ui = ui, server = server)
    

    To remove:

    1. add an ID argument to your panel, and use removeUI to remove it. Remember to change the ID in you own case.

    To hide/show:

    1. We can use toggle from shinyjs to show or hide some elements we choose.
    2. Use updateActionButton to also change it text when hidden.

    enter image description here