Conditionally show or hide required inputs
The word cloud app now has three different ways to supply words to the word cloud. Two of these methods involve a specific UI element that is only useful for them: there is a textarea that is only used when the user selects the "own" word source, and there is a file input that is only relevant when the user chooses the "file" source. Ideally, only inputs that are needed would appear at any given moment.
This exercise is part of the course
Case Studies: Building Web Applications with Shiny in R
Exercise instructions
The textarea has already been wrapped in a conditionalPanel()
so that it will only appear when the user chooses to input their own text. Your task is to conditionally show the file input only when the user selects the file upload as the data source. Specifically:
- Wrap the file input in a conditional panel (line 19).
- The condition for the panel needs to be met when the user chooses the "file" option from the data source radio buttons (line 22).
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
ui <- fluidPage(
h1("Word Cloud"),
sidebarLayout(
sidebarPanel(
radioButtons(
inputId = "source",
label = "Word source",
choices = c(
"Art of War" = "book",
"Use your own words" = "own",
"Upload a file" = "file"
)
),
conditionalPanel(
condition = "input.source == 'own'",
textAreaInput("text", "Enter text", rows = 7)
),
# Wrap the file input in a conditional panel
___(
# The condition should be that the user selects
# "file" from the radio buttons
condition = ___,
fileInput("file", "Select a file")
),
numericInput("num", "Maximum number of words",
value = 100, min = 5),
colourInput("col", "Background color", value = "white")
),
mainPanel(
wordcloud2Output("cloud")
)
)
)
server <- function(input, output) {
data_source <- reactive({
if (input$source == "book") {
data <- artofwar
} else if (input$source == "own") {
data <- input$text
} else if (input$source == "file") {
data <- input_file()
}
return(data)
})
input_file <- reactive({
if (is.null(input$file)) {
return("")
}
readLines(input$file$datapath)
})
output$cloud <- renderWordcloud2({
create_wordcloud(data_source(), num_words = input$num,
background = input$col)
})
}
shinyApp(ui = ui, server = server)