Search code examples
rshinyshinydashboardshiny-reactivityshinyjs

Update color of actionlink in shiny


I want to change colour of the actionLink once it is clicked. I could not find any post which will achieve this.

What I found:

  1. R Shiny toggle text of actionLink
  2. shiny module: update color of button

But these were of no help. Here is the sample code from the answer from the first link (by @Julien Navarre)

library(shiny)
library(shinyjs)
shinyApp(
  ui = shinyUI(
    fluidPage(useShinyjs(),
              actionLink("button", "Show additional"),
              hidden(div(id='text_div', verbatimTextOutput("text")))
    )
  ),

  server = function(input, output, session){
    observeEvent(input$button, {
      toggle('text_div')
      output$text <- renderText({"Additional"})

      if (input$button %% 2 == 1) {
        txt <- "Hide Additional"
      } else {
        txt <- "Show Additional"
      }
      updateActionButton(session, "button", label = txt)
    })

  }
)

In this code, once the label is changed, the colour of the label should also change. For example, Show Additional link should have a green colour, whereas Hide Additional should have red colour.

I tried updateactionLink with color argument but there is no such argument.

How can I achieve this?


Solution

  • One way would be to use css and addClass, removeClass from {shinyjs}:

    library(shiny)
    library(shinyjs)
    
    shinyApp(
      ui = shinyUI(
        fluidPage(useShinyjs(),
                  
                  tags$head(
                    tags$style(HTML("
                      a.action-button {
                        color: #00ff00;
                      }
                      a.action-button.red {
                        color: #ff0000;
                      }"))
                  ),
                  
                  actionLink("button", "Show additional"),
                  
                  hidden(div(id='text_div', verbatimTextOutput("text")))
        )
      ),
      
      server = function(input, output, session){
        
        observeEvent(input$button, {
          
          if (input$button %% 2 == 1) {
            txt <- "Hide Additional"
            shinyjs::addClass("button", "red")
          } else {
            txt <- "Show Additional"
            shinyjs::removeClass("button", "red")
          }
          
          toggle('text_div')
          output$text <- renderText({"Additional"})
    
          updateActionButton(session, "button", label = txt)
        })
        
      }
    )