Home > Enterprise >  Have multiple actionButtons linked to the same verbatimTextOutput
Have multiple actionButtons linked to the same verbatimTextOutput

Time:12-01

I'm trying to create a shiny app with multiple actionButtons that render unique text to the same varbatimTextOutput. I'd like it to work like this, where buttons 1 and 2 would print different text to the same place:

enter image description here

Here's what I tried:

library(shiny)

ui <- fluidPage(
  actionButton("button1", "Button 1"),
  actionButton("button2", "Button 2"),
  verbatimTextOutput("button_out", placeholder = TRUE)
)

server <- function(input, output) {
  button_out <- eventReactive({
    input$button1
    }
    ,{
      paste0("You pressed button 1!")
    }) 
  
  button_out <- eventReactive({
    input$button2
    }
    ,{
      paste0("You pressed button 2!")
    }) 
  
  output$button_out <- renderText({
    button_out()
    })
}
  
shinyApp(ui = ui, server = server)

I was expecting this to allow both actionButtons to output to the same place, but instead only Button 2 works, I guess because the code for that is overwriting the code for button 1. I considered putting an if statement in eventReactive, but I'm not exactly sure how to do it?

Is there a way to do this that I'm not seeing?

CodePudding user response:

@YBS's answer is nice.

Another way is to use the onclick attribute of the buttons. This attribute allows to execute some JavaScript code each time the button is clicked. Then with this JavaScript code you can send a Shiny input value to the server with Shiny.setInputValue

library(shiny)

ui <- fluidPage(
  actionButton(
    "button1", "Button 1", 
    onclick = "Shiny.setInputValue('button', 1);"
  ),
  actionButton(
    "button2", "Button 2", 
    onclick = "Shiny.setInputValue('button', 2);"
  ),
  verbatimTextOutput("button_out", placeholder = TRUE)
)

server <- function(input, output) {
  
  output$button_out <- renderText({
    paste0("You clicked on button ", input$button) 
  })
}
  
shinyApp(ui = ui, server = server)

CodePudding user response:

One way to do it is use reactiveValues object. Try this

ui <- fluidPage(
  actionButton("button1", "Button 1"),
  actionButton("button2", "Button 2"),
  verbatimTextOutput("button_out", placeholder = TRUE)
)

server <- function(input, output) {
  
  rv <- reactiveValues(val=NULL)
  
  observeEvent(input$button1, {
    rv$val <- paste0("You pressed button 1!")
  }) 
  
  observeEvent(input$button2, {
    rv$val <- paste0("You pressed button 2!")
  })
  
  output$button_out <- renderText({
    rv$val
  })
}

shinyApp(ui = ui, server = server)
  • Related