reset R shiny actionButton to use it more than once
Asked Answered
F

1

6

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

Flag answered 9/5, 2018 at 12:38 Comment(0)
R
8

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)
Railroader answered 9/5, 2018 at 12:55 Comment(3)
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.Radarman
@Radarman Have you checked this? #41961453Railroader
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.Radarman

© 2022 - 2024 — McMap. All rights reserved.