I'm facing an issue in my Shiny app where the shinyjs::show()
and shinyjs::hide()
functions are not working as expected when used inside a server module. Oddly enough, when I use shinyjs::runjs()
to execute the equivalent jQuery commands directly, everything works perfectly.
My app.R file:
ui <- fluidPage(
useShinyjs(),
div(id = "login_page", loginUI("login")),
div(id = "main_ui", mainMenuUI("main_menu"), style = "display:none;")
)
server <- function(input, output, session) {
callModule(loginServer, "login")
callModule(mainMenuServer, "main_menu")
}
My login_module.R:
> loginUI <- function(id) {
> ns <- NS(id)
> tagList(
> div(class = "text-center", h3("Bienvenido al Sistema de Gestión de Calidad del Agua")),
> textInput(ns("user_name"), "Usuario", placeholder = "Introduce tu nombre de usuario"),
> passwordInput(ns("password"), "Contraseña", placeholder = "Introduce tu contraseña"),
> actionButton(ns("login_button"), "Iniciar Sesión")
> )
> }
>
> loginServer <- function(input, output, session) {
> observeEvent(input$login_button, {
> if (input$user_name == "admin" && input$password == "admin") {
> showNotification("Login successful", type = "message")
> shinyjs::hide("login_page")
> shinyjs::show("main_ui")
> } else {
> showNotification("Invalid username or password", type = "error")
> }
> })
> }
The problem:
-
When I click the login button with the correct credentials, the
shinyjs::hide("login_page")
and shinyjs::show("main_ui")` calls do not seem to work; nothing happens on the UI. -
However, if I replace those lines with
shinyjs::runjs("$('#login_page').hide();")
and shinyjs::runjs("$('#main_ui').show();")`, the UI updates as expected.
What I’ve tried:
- Verified that the elements
#login_page
and#main_ui
exist in the DOM using document.getElementById` in the browser console. Both elements are present. - Attempted using
shinyjs::delay()
to ensure the DOM was fully loaded, but this didn’t resolve the issue. - Checked for conflicting CSS or JavaScript that might be interfering, but didn’t find anything significant.
Environment:
- R version: 4.2
- Shiny version: 1.9.1
- shinyjs version: 2.1.0
- Running on: Windows 10 (With R Tools installed)
Any insights or suggestions would be greatly appreciated!
Thank you in advance.