3.1 Structure of a Shiny App

A simple shiny app is a directory containing two R scripts, one is ui.R, which controls the layout and appearance of your app, the other is server.R, which contains the instructions that your computer needs to build your app. Note that the names for the scripts are fixed, you should NOT use other names.

Exercise 1: App template

Let’s create a new directory named 01-hello (or whatever you like) and then create two empty ui.R and server.R files within it.

Open ui.R with any editor you want and put the following code in it:

library(shiny)
fluidPage()

Then copy the following code to server.R. Note that the server.R contains one single unnamed function.

library(shiny)
function(input, output) {
}

For historical reasons, usually shinyUI and shinyServer functions are used to wrap the UI and server side scripts, but it is no longer required as of Shiny 0.10.

To run the app,

  1. you can switch the R working directory to the directory above 01-hello and run
library(shiny)
runApp('01-hello')
  1. or you can switch the R working directory to 01-hello and run
library(shiny)
runApp()
  1. just click the Run App button if you use Rstudio (Recommended)

After running the app, you’ll get an empty web page.

Single-file Shiny App

As the name implied, a single-file shiny app consists of a single file called app.R which contains both the server and UI components. As an example, we can rewrite Exercise 1 into a single-file shiny app with the following code in the app.R file:

library(shiny)
ui <- fluidPage()
server <- function(input, output){}
shinyApp(ui = ui, server = server)