Kira Tebbe Kira Tebbe - 2 months ago 6
R Question

Shiny: add button label to sidebar & update buttons after click

I'm a bit rusty to Shiny reactivity, but I want to do two things when a button is clicked:


  1. add that button label to the sidebar (and add more labels to sidebar after more clicks)

  2. update the button labels (i.e. more random integers)



I'm nervous about changing the label before recording it, so I want to get the timing right. Here's a skeleton of what I'm working with:

library(shiny)

ui <- fluidPage(
sidebarLayout(
sidebarPanel(
textOutput("clicks")
),
mainPanel(
uiOutput("button1"),
uiOutput("button2")
))
)
###################
server <- function(input, output, session) {

output$clicks <- renderText({
paste()
})

## reactive values
inside <- reactive({
inside <- sample(1:100,2)
})

## buttons
output$button1 <- renderUI({
actionButton("course1", label = inside()[1], style='padding:50px')
})
output$button2 <- renderUI({
actionButton("course2", label = inside()[2], style='padding:50px')
})
}

shinyApp(ui = ui, server = server)


Right now the sidebar is blank because I'm not sure how to add it, or what to add to make the button labels update after a click (whether to do it inside a
reactive
value or an
observeEvent
). Any help is much appreciated!

Answer

Here's a way to do it with reactiveValues:

library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel( 
      textOutput("clicks")
    ),
    mainPanel(
      uiOutput("button1"), 
      uiOutput("button2")
    ))
)
###################
server <- function(input, output, session) {
  # Show history
  output$clicks <- renderText({
    history[['clicked']]
  })

  ## reactive values
  # store history as reactive values
  history <- reactiveValues(clicked = c())
  # update history when a button is clicked
  observeEvent(input$course1,{
    history[['clicked']] <- c(history[['clicked']],inside()[1])
  })

  observeEvent(input$course2,{
    history[['clicked']] <- c(history[['clicked']],inside()[2])
  })
  #update inside when history updates
  inside <- reactive({
    history[['clicked']]
    inside <- sample(1:100,2)
  })

  ## buttons
  output$button1 <- renderUI({
    actionButton("course1", label = inside()[1], style='padding:50px')
  })
  output$button2 <- renderUI({
    actionButton("course2", label = inside()[2], style='padding:50px')
  })
}

shinyApp(ui = ui, server = server)
Comments