How do I update button labels in R Shiny?

The R Shiny website has a great example on how to update labels and values โ€‹โ€‹of various input types based on user input. However, I couldn't find anything for the buttons. Specifically, how do I update the label for a button based on user input?

+3


source to share


3 answers


You can dynamically create a button like this by updating the labels at the same time:



library(shiny)

ui =(pageWithSidebar(
  headerPanel("Test Shiny App"),
  sidebarPanel(
    textInput("sample_text", "test", value = "0"),
    #display dynamic UI
    uiOutput("my_button")),
  mainPanel()
))

server = function(input, output, session){
  #make dynamic button
  output$my_button <- renderUI({
    actionButton("action", label = input$sample_text)
  })
}
runApp(list(ui = ui, server = server))

      

+5


source


If your button is already built, the solution should use the "shinyjs" library.



library(shinyjs)
 # in UI section
shinyjs::useShinyjs()
 # in Server section: call this function at any time to update the button label
runjs(paste0("$('label[for=\"YourButtonId\"]').text('",TextVariable,"')"))

      

+2


source


updateActionButton

:

ui <- fluidPage(
  actionButton('someButton', ""),
  textInput("newLabel", "new Button Label:", value = "some label")
)

server <- function(input, output, session) {

  observeEvent(input$newLabel, {
    updateActionButton(session, "someButton", label = input$newLabel)
  })
}

shinyApp(ui, server)

      

0


source







All Articles