JeanBertin
JeanBertin

Reputation: 703

reset R shiny actionButton to use it more than once

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

Upvotes: 6

Views: 6422

Answers (1)

mbh86
mbh86

Reputation: 6368

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)

Upvotes: 8

Related Questions