Table of content for chapter 02

Chapter section list

2.1 Introduction

In this chapter, we’ll focus on the front end, and give you a whirlwind tour of the HTML inputs and outputs provided by Shiny. We’ll mostly stick to the inputs and outputs built into Shiny itself. However, there is a rich and vibrant community of extension packages, like

You can find a comprehensive, actively-maintained list of packages supporting {shiny} at , maintained by Nan Xiao.

2.2 Inputs

2.2.1 Common structure

There are three common parameters:

  1. inputID: All input functions have the same first argument: inputId. This is the identifier used to connect the front end with the back end: if your UI has an input with ID "name", the server function will access it with input$name. The inputId has two constraints:
    • It must be a simple string that contains only letters, numbers, and underscores (no spaces, dashes, periods, or other special characters allowed!). Name it like you would name a variable in R.
    • It must be unique. If it’s not unique, you’ll have no way to refer to this control in your server function!
  2. label: Most input functions have a second parameter called label. This is used to create a human-readable label for the control. Shiny doesn’t place any restrictions on this string.
  3. value: The third parameter is typically value, which, where possible, lets you set the default value.

Remaining parameters are unique to the specific control.

When creating an input, I recommend supplying the inputId and label arguments by position, and all other arguments by name:

sliderInput("min", "Limit (minimum)", value = 50, min = 0, max = 100)
Note

The following sections describe the inputs built into Shiny, loosely grouped according to the type of control they create. The goal is to give you a rapid overview of your options, not to exhaustively describe all the arguments. Read the documentation to get the full details!

2.2.2 Free text

Collect small amounts of text with textInput(), passwords with passwordInput(), and paragraphs of text with textAreaInput().

Watch out!

All passwordInput() does is hide what the user is typing, so that someone looking over their shoulder can’t read it. It’s up to you to make sure that any passwords are not accidentally exposed, so we don’t recommend using passwords unless you have had some training in secure programming.

If you want to ensure that the text has certain properties you can use shiny::validate(), which we’ll come back to in Chapter 8.

2.2.3 Numeric input

To collect numeric values, create a constrained text box with numericInput() or a slider with sliderInput(). If you supply a length-2 numeric vector for the default value of sliderInput(), you get a “range” slider with two ends.

Sliders are extremely customisable and there are many ways to tweak their appearance. See Slider Input Widget — sliderInput and Using sliders for more details. See also my experiments in Section B.1.

2.2.4 Dates

Collect a single day with shiny::dateInput() or a range of two days with shiny::dateRangeInput(). These provide a convenient calendar picker, and additional arguments like datesdisabled and daysofweekdisabled allow you to restrict the set of valid inputs.

Date format, language, and the day on which the week starts defaults to US standards. If you are creating an app with an international audience, set format, language, and weekstart so that the dates are natural to your users.

2.2.5 Limited choices

2.2.5.1 Introduction

There are two different approaches to allow the user to choose from a prespecified set of options: shiny::selectInput() and shiny::radioButtons().

Code Collection 2.4 : Limited choices

R Code 2.7 : Limited choices: drop-down menu and radio buttons

Code
library(shiny)

animals <- c("dog", "cat", "mouse", "bird", "other", "I hate animals")

ui <- fluidPage(
  selectInput("state", "What's your favourite state?", state.name),
  radioButtons("animal", "What's your favourite animal?", animals)
)

server <- function(input, output, session) {

}

shinyApp(ui, server)

See my experiment in Section B.2.

2.2.5.2 Radio buttons

Radio buttons have two nice features:

  • they show all possible options, making them suitable for short lists, and
  • via the choiceNames/choiceValues arguments, they can display options other than plain text.
    • choiceNames determines what is shown to the user;
    • choiceValues determines what is returned in your server function.

2.2.5.4 Check boxes

There’s no way to select multiple values with radio buttons, but there’s an alternative that’s conceptually similar: shiny::checkboxGroupInput(). For a checkbox for a single yes/no question, use shiny::checkboxInput():

2.2.6 File uploads

shiny::fileInput() requires special handling on the server side, and is discussed in detail in Chapter 9.

2.2.7 Action buttons

Let the user perform an action with shiny::actionButton() or shiny::actionLink(): Actions links and buttons are most naturally paired with shiny::observeEvent() or shiny::eventReactive() in your server function. You haven’t learned about these important functions yet, but we’ll come back to them in Section 3.5.

You can customize the appearance using the class argument by using one of "btn-primary", "btn-success", "btn-info", "btn-warning“, or "btn-danger". You can also change the size with "btn-lg”, "btn-sm", "btn-xs“. Finally, you can make buttons span the entire width of the element they are embedded within using "btn-block".

The class argument works by setting the class attribute of the underlying HTML, which affects how the element is styled. To see other options, you can read the documentation for Bootstrap, the CSS design system used by Shiny.

2.2.8 Exercises

2.2.8.1 Label as placeholder

Exercise 2.1 : Use label as placeholder

When space is at a premium, it’s useful to label text boxes using a placeholder that appears inside the text entry area. How do you call shiny::textInput() to generate the UI below?

Solution 2.9. : Use label as placeholder

Code
library(shiny)

ui <- fluidPage(
    textInput(
        "name", 
        label = NULL, 
        placeholder = label
        )
)

server <- function(input, output, session) {

}

shinyApp(ui, server)

2.2.8.2 Create a date slider

Exercise 2.2 : Create a date slider

2.2.8.3 Slider animation

Exercise 2.3 : Slider animation

Create a slider input to select values between 0 and 100 where the interval between each selectable value on the slider is 5. Then, add animation to the input widget so when the user presses play the input widget scrolls through the range automatically.

Solution 2.5. : Slider animation

Code
ui <- fluidPage(
    sliderInput(
        "num",
        "Press play button",
        min = 0,
        max = 100,
        value = 0,
        step = 5,
        animate = animationOptions(
            interval = 1000,
            loop = TRUE,
            playButton = "Play",
            pauseButton = "Stop"
        )
    )
)

server <- function(input, output, session) {

}

shinyApp(ui, server)

Solution 2.6. : Slider animation

#| '!! shinylive warning !!': |
#|   shinylive does not work in self-contained HTML documents.
#|   Please set `embed-resources: false` in your metadata.
#| standalone: true
#| viewerHeight: 150

ui <- fluidPage(
    sliderInput(
        "num",
        "Press play button",
        min = 0,
        max = 100,
        value = 0,
        step = 5,
        animate = animationOptions(
            interval = 1000,
            loop = TRUE,
            playButton = "Play",
            pauseButton = "Stop"
        )
    )
)

server <- function(input, output, session) {

}

shinyApp(ui, server)

2.3 Outputs

Outputs in the UI create placeholders that are later filled by the server function. Like inputs, outputs take a unique ID as their first argument: if your UI specification creates an output with ID "plot", you’ll access it in the server function with output$plot.

Each output function on the front end is coupled with a render function in the back end. There are three main types of output, corresponding to the three things you usually include in a report: text, tables, and plots. The following sections show you the basics of the output functions on the front end, along with the corresponding render functions in the back end.

2.3.1 Text

Output regular text with shiny::textOutput() and fixed code and console output with shiny::verbatimTextOutput().

Code Collection 2.10 : Text output examples

R Code 2.19 : Text output examples

Code
library(shiny)

ui <- fluidPage(
  textOutput("text"),
  verbatimTextOutput("code")
)
server <- function(input, output, session) {
  output$text <- renderText({ 
    "Hello friend!" 
  })
  output$code <- renderPrint({ 
    summary(1:10) 
  })
}

shinyApp(ui, server)

Note that the {} are only required in render functions if you need to run multiple lines of code. As you’ll learn shortly, you should do as little computation in your render functions as possible, which means you can often omit them.

R Code 2.20 : Text output examples

Code
library(shiny)

ui <- fluidPage(
  textOutput("text"),
  verbatimTextOutput("code")
)
server <- function(input, output, session) {
  output$text <- renderText("Hello friend!")
  output$code <- renderPrint(summary(1:10))
}

shinyApp(ui, server)

Here’s what the server function would look like if written more compactly.

R Code 2.21 : Text output examples

#| '!! shinylive warning !!': |
#|   shinylive does not work in self-contained HTML documents.
#|   Please set `embed-resources: false` in your metadata.
#| standalone: true
#| viewerHeight: 150

ui <- fluidPage(
  textOutput("text"),
  verbatimTextOutput("code")
)
server <- function(input, output, session) {
  output$text <- renderText({ 
    "Hello friend!" 
  })
  output$code <- renderPrint({ 
    summary(1:10) 
  })
}

shinyApp(ui, server)

R Code 2.22 : Text output examples

#| '!! shinylive warning !!': |
#|   shinylive does not work in self-contained HTML documents.
#|   Please set `embed-resources: false` in your metadata.
#| standalone: true
#| viewerHeight: 150

ui <- fluidPage(
  textOutput("text"),
  verbatimTextOutput("code")
)

server <- function(input, output, session) {
  output$text <- renderText("Hello friend!")
  output$code <- renderPrint(summary(1:10))
}

shinyApp(ui, server)

Note that there are two render functions which behave slightly differently:

2.3.2 Tables

There are two options for displaying data frames in tables:

tableOutput() is most useful for small, fixed summaries (e.g. model coefficients); dataTableOutput() is most appropriate if you want to expose a complete data frame to the user.

If you want greater control over the output of dataTableOutput(), I highly recommend the {reactable} package by Greg Lin (Lin 2023).

Code Collection 2.12 : Table output examples

R Code 2.25 : Table output examples

Code
library(shiny)

ui <- fluidPage(
  tableOutput("static"),
  dataTableOutput("dynamic")
)

server <- function(input, output, session) {
  output$static <- renderTable(head(mtcars))
  output$dynamic <- renderDataTable(mtcars, options = list(pageLength = 5))
}

shinyApp(ui, server)

shiny::renderDataTable() is deprecated as of shiny 1.8.1. Please use DT::renderDT() instead. Since you have a suitable version of DT (>= v0.32.1), shiny::renderDataTable() will automatically use DT::renderDT() under-the-hood. If this happens to break your app, set options(shiny.legacy.datatable = TRUE) to get the legacy datatable implementation (or FALSE to squelch this message). See https://rstudio.github.io/DT/shiny.html for more information.

Watch out!

There are no warning/error messages in the {shinylive-r} mode. For debugging purposes it is necessary to use the standard app.R file approach.

R Code 2.26 : Table output examples

Code
library(shiny)

ui <- fluidPage(
    tableOutput("static"),
    DT::DTOutput("dynamic")
)

server <- function(input, output, session) {
    output$static <- renderTable(head(mtcars))
    output$dynamic <- DT::renderDT(mtcars, options = list(pageLength = 5))
}

shinyApp(ui, server)

If I had used library(DT) then I wouldn’t needed DT:: in front of the {DT} functions.

Note

But there is an important difference: Using the library(<package-name>) function downloads several packages via https://repo.r-wasm.org/ (The WebR binary R package repository contains more than 15,000 packages that have been built for WebAssembly and are available for download from this repository). I think therefore that is generally better to use the <package-name>:: mode if there are used only some functions from the package in question.

2.3.3 Plots

You can display any type of R graphic (base, {ggplot2}, or otherwise) with plotOutput() and renderPlot().

By default, plotOutput() will take up the full width of its container (more on that shortly), and will be 400 pixels high. You can override these defaults with the height and width arguments. We recommend always setting res = 96 as that will make your Shiny plots match what you see in RStudio as closely as possible.

Plots are special because they are outputs that can also act as inputs. plotOutput() has a number of arguments like click, dblclick, and hover. If you pass these a string, like click = "plot_click", they’ll create a reactive input (input$plot_click) that you can use to handle user interaction on the plot, e.g. clicking on the plot. We’ll come back to interactive plots in Shiny in Chapter 7.

2.3.4 Downloads

You can let the user download a file with downloadButton() or downloadLink(). These require new techniques in the server function, so we’ll come back to that in Chapter 9.

2.3.5 Exercises

2.3.5.1 Render function to pair

Exercise 2.5 : Render function to pair

Which of textOutput() and verbatimTextOutput() should each of the following render functions be paired with?

  1. renderPrint(summary(mtcars))
  2. renderText("Good morning!")
  3. renderPrint(t.test(1:5, 2:6))
  4. renderText(str(lm(mpg ~ wt, data = mtcars)))

Solution 2.9. : Use label as placeholder

Which of textOutput() and verbatimTextOutput() should each of the following render functions be paired with?

  1. renderPrint(summary(mtcars)): verbatimTextOutput()
  2. renderText("Good morning!"): textOutput()
  3. renderPrint(t.test(1:5, 2:6)): verbatimTextOutput()
  4. renderText(str(lm(mpg ~ wt, data = mtcars))): textOutput()

2.3.5.2 Plot dimensions and alt-tag

Exercise 2.6 : Change plot dimensions and add alt-tag

Re-create the Shiny app from Section 2.3.3, this time setting height to 300px and width to 700px. Set the plot “alt” text so that a visually impaired user can tell that its a scatterplot of five random numbers.

Solution 2.10. : Plot dimensions and alt-tag

Code
library(shiny)

ui <- fluidPage(
    plotOutput("plot", height = "300px", width = "700px"),
)

server <- function(input, output, session) {
    output$plot <- renderPlot(
        plot(1:5), 
        res = 96,
        alt = "Scatterplot of five random numbers")
}

shinyApp(ui, server)

2.3.5.3 DT::renderDT() options

Exercise 2.7 : DT::renderDT() options

Update the options in the call to DT::renderDT() below so that the data is displayed, but all other controls are suppressed (i.e., remove the search, ordering, and filtering commands). You’ll need to read Using DT in shiny and review the more complex DT options.

R Code 2.31 : Standard DT::renderDT() options

Code
library(shiny)

ui <- fluidPage(
  DT::DTOutput("table")
)

server <- function(input, output, session) {
  output$table <- DT::renderDT(mtcars, options = list(pageLength = 5))
}

shinyApp(ui, server)

Solution 2.12. : Change DT::renderDT() options

Code
library(shiny)

ui <- fluidPage(
    DT::DTOutput("table")
)

server <- function(input, output, session) {
    output$table <- DT::renderDT(
        mtcars,
        options = list(
            pageLength = 5,
            searching = FALSE,
            ordering = FALSE,
            lengthChange = FALSE
        )
    )
}

shinyApp(ui, server)

2.3.5.4 Use {reactable}

2.4 Summary

This chapter has introduced the major input and output functions that make up the front end of a Shiny app. This was a big info dump, so don’t expect to remember everything after a single read. Instead, come back to this chapter when you’re looking for a specific component: you can quickly scan the figures, and then find the code you need.

In the next chapter, we’ll move on to the back end of a Shiny app: the R code that makes your user interface come to life.

References

Attali, Dean. 2023. “Colourpicker: A Colour Picker Tool for Shiny and for Selecting Colours in Plots.” https://doi.org/10.32614/CRAN.package.colourpicker.
Lin, Greg. 2023. “Reactable: Interactive Data Tables for r.” https://doi.org/10.32614/CRAN.package.reactable.
Perrier, Victor, Fanny Meyer, and David Granjon. 2025. “shinyWidgets: Custom Inputs Widgets for Shiny.” https://doi.org/10.32614/CRAN.package.shinyWidgets.
Vries, Andrie de, Barret Schloerke, and Kenton Russell. 2023. “Sortable: Drag-and-Drop in ’Shiny’ Apps with ’SortableJS’.” https://doi.org/10.32614/CRAN.package.sortable.