rshinyaction-button

Take action when any of the button is clicked Shiny R


How to observe when any of the multiple buttons is clicked? For example, we have three buttons, I would like to show the notification when any of the buttons is clicked. Here is an example code

library(shiny)


ui <- fluidPage(
  actionButton('button1', 'button1'),actionButton('button2', 'button2'),actionButton('button3', 'button3'))

server <- function(input, output, session) {
  
  
  
  
  
  observe({
    
    req(input$button1, input$button2, input$button3)
    
    
    showNotification("This is a notification.")
    
    
    
  })
}

shinyApp(ui, server)

The above code is not satisfactory because when initiate the page, only when three buttons are all clicked, notification shows.

Also, is it possible to know which button is cliecked?

Thanks.


Solution

  • Use observeEvent instead and put all your triggers in c()

    library(shiny)
    
    
    ui <- fluidPage(
        actionButton('button1', 'button1'),actionButton('button2', 'button2'),actionButton('button3', 'button3'))
    server <- function(input, output, session) {
        observeEvent(c(input$button1, input$button2, input$button3), ignoreInit = TRUE, {
            showNotification("This is a notification.")
        })
    }
    
    shinyApp(ui, server)