Search code examples
rshinyshinydashboard

How to close a modal


I have a modal that displays when the page is accessed. When the button is clicked on Auth the modal should close. In the server part, I used an observeEvent on the b_auth (Auth button ID ) and put the removeModal() function. When I click the Auth button, the modal does not close.

library(shiny); library(shinydashboard)

fmodal <- function(){modalDialog(id = "authModal",title = "title", textOutput("modalMessage"), textInput("username", "username", value = "username"), passwordInput("password", "password", value = "password"), footer = tagList(
      actionButton("b_auth", "Auth"), modalButton("Cancel")))
}

ui <- dashboardPage(dashboardHeader(title = "Basic dashboard"), dashboardSidebar(sidebarMenu(menuItem("Accueil", tabName = "dashboard", icon = icon("dashboard")))), dashboardBody(tabItems(tabItem(tabName = "dashboard",
fmodal() ))))

server <- function(input, output, session) {
  observeEvent(input$b_auth, {
    removeModal() })}

shinyApp(ui = ui, server = server)

Solution

  • Moving the modal to the server works:

    library(shiny); library(shinydashboard)
    
    fmodal <- function(){modalDialog(id = "authModal",title = "title", textOutput("modalMessage"), textInput("username", "username", value = "username"), passwordInput("password", "password", value = "password"), footer = tagList(
        actionButton("b_auth", "Auth"), modalButton("Cancel")))
    }
    
    ui <- dashboardPage(dashboardHeader(title = "Basic dashboard"), dashboardSidebar(sidebarMenu(menuItem("Accueil", tabName = "dashboard", icon = icon("dashboard")))), dashboardBody(tabItems(tabItem(tabName = "dashboard"))))
    
    server <- function(input, output, session) {
        
        showModal(fmodal())
        
        observeEvent(input$b_auth, {
            removeModal() })}
    
    shinyApp(ui = ui, server = server)