5

Does someone know how to make actionButton (R shiny) reset to initial value in order to use it more than once?

Please find below a reproductible example:

In this example, I would like to change the chart color by selecting the corresponding button: my issue is that it cannot reload the chart after one iteration.

library(shiny)

ui <- fluidPage(

  actionButton(inputId = "button1",label = "Select red"),
  actionButton(inputId = "button2",label = "Select blue"),
  plotOutput("distPlot")

)


server <- function(input, output) {

   output$distPlot <- renderPlot({
      x    <- faithful[, 2] 
      bins <- seq(min(x), max(x))

      my_color <- "green"
      if (input$button1){my_color <- "red"}
      if (input$button2){my_color <- "blue"}

      hist(x, breaks = bins, col = my_color)
   })
}

shinyApp(ui = ui, server = server)

Thank you in advance

JeanBertin
  • 633
  • 1
  • 7
  • 23

1 Answers1

7

It's not good idea to reset ActionButton in Shiny usually. I would suggest you to use ObserveEvent and store the color into reactiveValues.

library(shiny)

ui <- fluidPage(
  actionButton(inputId = "button1", label = "Select red"),
  actionButton(inputId = "button2", label = "Select blue"),
  plotOutput("distPlot")
)


server <- function(input, output) {
  r <- reactiveValues(my_color = "green")

  output$distPlot <- renderPlot({
    x <- faithful[, 2]
    bins <- seq(min(x), max(x))
    hist(x, breaks = bins, col = r$my_color)
  })

  observeEvent(input$button1, {
    r$my_color <- "red"
  })

  observeEvent(input$button2, {
    r$my_color <- "blue"
  })
}

shinyApp(ui = ui, server = server)
mbh86
  • 6,078
  • 3
  • 18
  • 31
  • Do you know if this is also possible with only one `observeEvent`? and a `ifelse` or `case_when` function? like: `observeEvent(c(input$button1, input$button2){ r$my_color <- case_when(input$button1 > 0 ~ "red", input$button2 > 0 ~ "blue" })` I can't really get something like this to work. – Kevin Mar 19 '21 at 14:42
  • @Kevin Have you checked this? https://stackoverflow.com/questions/41960953/how-to-listen-for-more-than-one-event-expression-within-a-shiny-observeevent – mbh86 Mar 24 '21 at 09:13
  • Yes I have seen that one, however it does not work for my case. After using all the color options once, the Shiny-app freezes. The above solution works better in my case. Thanks for the suggestion. – Kevin Mar 26 '21 at 10:39