Reputation: 546
Is it possible to create modules in a Shiny App which is written down in separated app.R, server.R and ui.R files?
All the examples I found are one app.R file with embedded server and ui functions in. See example 1, example 2!, example 3!
(I took the code from this last example for this test).
I tried to run this app:
app.R
library(shiny)
# load module functions
source("hello_world.R")
# Run the application
shinyApp(ui = ui, server = server)
ui.R
#ui.R
library(shiny)
#source("hello_world.R")
ui <- fluidPage(
titlePanel("Using of Shiny modules"),
fluidRow(
# Call interface function of module "hello_world"
hello_worldUI(id = "id_1")
)
)
server.R
#server.R
library(shiny)
source("hello_world.R")
server <- function(input, output, session) {
# Call logic server function of module "hello_world"
callModule(module = hello_world, id = "id_1")
}
# UPDATE! -> my Error comes from this line of code in server.R file:
#shinyApp(ui = ui, server = server)
#Removing the line above solve the problem.
hello_world.R
#module 1: hello_world
# Function for module UI
hello_worldUI <- function(id) {
ns <- NS(id)
fluidPage(
fluidRow(
column(2, textInput(ns("TI_username"), label = NULL, placeholder = "your name")),
column(2, actionButton(ns("AB_hello"), label = "Hello !"))
),
hr(),
fluidRow(
column(12, textOutput(ns("TO_Hello_user")))
)
)
}
# Function for module server logic
hello_world <- function(input, output, session) {
# When user clicks on "Hello" button : Update reactive variable "name"
name <- eventReactive(input$AB_hello, {
return(input$TI_username)
})
# Show greetings
output$TO_Hello_user <- renderText({
if (name() %in% "") {
return("Hello world !")
} else {
return(paste("Hello", name(), "!"))
}
})
}
But I got this error:
Warning: Error in force: object 'ui' not found
52: force
51: uiHttpHandler
50: shinyApp
Error in force(ui) : object 'ui' not found
Upvotes: 0
Views: 2350
Reputation: 2384
The ui
and server
objects are not known to the app unless you define them in the same file and they are generated at run time, or you explicitly call them from outside files before shinyApp()
. Change your app.R
like below, and it should work:
library(shiny)
# load module functions
source("hw.R")
# load ui elements
source("ui.R")
# load server function
source("serv.R")
# Run the application
shinyApp(ui = ui, server = server)
Upvotes: 4