Trigger reactions with observeEvent()
There are times when you want to perform an action in response to an event. For example, you might want to let the app user download a table as a CSV file, when they click on a "Download" button. Or, you might want to display a notification or modal dialog, in response to a click.
The observeEvent()
function allows you to achieve this. It accepts two arguments:
- The event you want to respond to.
- The function that should be called whenever the event occurs.
In this exercise, you will use observeEvent()
to display a modal dialog with help text, when the user clicks on a button labelled "Help". The help text has
already been assigned to the variable bmi_help_text
.
This is a part of the course
“Building Web Applications with Shiny in R”
Exercise instructions
- UI:
- Add an action button named 'show_help', labelled "Help". You might have to scroll down or collapse the console to view the UI.
- Server:
- Uncomment the code
# showModal ...
- Wrap
showModal(...)
inobserveEvent()
so that the help text is displayed when a user clicks on the help button
- Uncomment the code
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
ui <- fluidPage(
titlePanel('BMI Calculator'),
sidebarLayout(
sidebarPanel(
textInput('name', 'Enter your name'),
numericInput('height', 'Enter your height in meters', 1.5, 1, 2),
numericInput('weight', 'Enter your weight in Kilograms', 60, 45, 120),
actionButton("show_bmi", "Show BMI")
# CODE BELOW: Add an action button named "show_help"
),
mainPanel(
textOutput("bmi")
)
)
)
server <- function(input, output, session) {
# MODIFY CODE BELOW: Wrap in observeEvent() so the help text
# is displayed when a user clicks on the Help button.
# Display a modal dialog with bmi_help_text
# MODIFY CODE BELOW: Uncomment code
# showModal(modalDialog(bmi_help_text))
rv_bmi <- eventReactive(input$show_bmi, {
input$weight/(input$height^2)
})
output$bmi <- renderText({
bmi <- rv_bmi()
paste("Hi", input$name, ". Your BMI is", round(bmi, 1))
})
}
shinyApp(ui = ui, server = server)