rshinymodule

Hide initially displayed code from shiny modularized app after clicking actionButton


I want to create a modularized shiny app which will initially display text but hide it after clicking actionButton(). Now the text always remains.My code:

(app.R)

library(shiny)
library(shinyjs)
library(shinydashboard)
library(shinyWidgets)
library(dplyr)

# Load the modules
source("sideUI.R")
source("sideServer.R")
source("textUI.R")
source("textServer.R")

# Build UI & server and then run the app
ui <- dashboardPage(
  dashboardHeader(title = "Text Hiding Example"),
  dashboardSidebar(sideUI("side")),  # Sidebar with the action button
  dashboardBody(
    useShinyjs(),  # Initialize shinyjs
    textUI("textPL")  # Text UI module
  )
)

server <- function(input, output, session) {
  # Use the reactive in another module
  btn_input <- sideServer("side")
  textServer("textPL", btn = btn_input$btn)
}

shinyApp(ui, server)

textUI.R

textUI <- function(id) {
  ns <- NS(id)
  
  tagList(
    div(
      id = ns("showtext"),
      p("This text will be hidden after clicking the button", style = "font-size: 16px; text-align: center;")
    )
  )
}

textServer.R

textServer <- function(id, btn) {
  moduleServer(
    id,
    function(input, output, session) {
      ns <- session$ns  # Namespace function

      # Observe button click event
      observeEvent(btn(), {
        shinyjs::hide(ns("showtext"))  # Hide the text with correct namespace
      })
    }
  )
}

sideUI.R

sideUI <- function(id) {
  ns <- NS(id)
  tagList(
    actionButton(ns("action"), "Hide Text")
  )
}

sideServer.R

sideServer <- function(id) {
  moduleServer(
    id,
    function(input, output, session) {
      return(btn = reactive(input$action))  # Return the button input as reactive
    }
  )
}

Solution

    1. In app.R, you should pass just btn_input, rather than btn_input$btn to the textServer() function.

    Specifically:

    server <- function(input, output, session) {
      # Use the reactive in another module
      btn_input <- sideServer("side")
      textServer("textPL", btn = btn_input)
    }
    
    1. In textServer.R, you should not wrap "showtext" in ns().

    Specifically:

    observeEvent(btn(), {
      shinyjs::hide("showtext")
    })