CommencerCommencer gratuitement

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:

  1. The event you want to respond to.
  2. 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.

Cet exercice fait partie du cours

Building Web Applications with Shiny in R

Afficher le cours

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(...) in observeEvent() so that the help text is displayed when a user clicks on the help button

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de 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)
Modifier et exécuter le code