Skip to content

Instantly share code, notes, and snippets.

@wch
Last active January 8, 2023 10:03
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wch/9606002 to your computer and use it in GitHub Desktop.
Save wch/9606002 to your computer and use it in GitHub Desktop.
actionButton demo for R Shiny

The actionButton is a substitute for submitButton, and it allows more control over which inputs will trigger re-execution of reactive objects. A submitButton simply stops all inputs on the page from sending their values to the server until the button is clicked.

When there's an actionButton on the client, the corresponding code on the server should use isolate(). Code that appears within an isolate() will not invalidate (and thus trigger the re-execution of) the reactive object.

In the example here, changes to input$n won't cause the code in renderPlot() to be re-executed, since it's used within isolate(). However, changes to input$goButton will cause the code in renderPlot() to re-execute. Each time the user clicks on the button, it will increment the numeric value of input$goButton, which will invalidate the reactive object and schedule it for re-execution.

Type: Shiny
Title: actionButton demo
License: MIT
Author: Winston Chang <winston@rstudio.com>
AuthorUrl: http://www.rstudio.com/
Tags: actionbutton
DisplayMode: Showcase
shinyServer(function(input, output) {
output$plot1 <- renderPlot({
# Simply accessing input$goButton here makes this reactive
# object take a dependency on it. That means when
# input$goButton changes, this code will re-execute.
input$goButton
# Use isolate() to avoid dependency on input$n
isolate({
hist(rnorm(input$n))
})
})
})
shinyUI(fluidPage(
titlePanel("actionButton example"),
fluidRow(
column(4, wellPanel(
sliderInput("n", "N:", min = 10, max = 1000, value = 200,
step = 10),
actionButton("goButton", "Go!"),
br(),
p("The plot won't update until the button is clicked.",
" Without the use of ", code("isolate()"),
" in server.R, the plot would update whenever the slider",
" changes.")
)),
column(8,
plotOutput("plot1")
)
)
))
@wilkinsonjason
Copy link

Thank you. This was quite helpful.

@davemcg
Copy link

davemcg commented Mar 12, 2017

Thanks, this made WAY more sense than what rstudio had

@clabornd
Copy link

Thanks

@sebastianBP26
Copy link

Very useful!
Thank you

@aliemrekaragul
Copy link

amazing work! thank you...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment