broesel23
broesel23

Reputation: 117

Iteratively highlight a row in shiny renderTable

For a shiny app, I'd like to go through a data frame row-wise and highlight (bold, color, or similiar) the selected row in renderTable. I was thinking of selecting the row by index. Can I do this with renderTable, or should I consider DT?

library(shiny)

ui <- 
  fluidRow(
    actionButton(
      "my_button",
      "Go to next row"
    ),
    tableOutput("my_table")
  )

server <- function(input, output){

  values <- reactiveValues()
  values$index <- 1
  values$dat <- iris

  observeEvent(
    input$my_button, {
      values$index <- values$index + 1
  })

  output$my_table <- 
    renderTable(values$dat) # somehow highlight the row at the index
}

shinyApp(ui = ui, server = server)

Upvotes: 1

Views: 568

Answers (1)

Lisa DeBruine
Lisa DeBruine

Reputation: 878

This might get you started.

library(shiny)
library(DT)
library(dplyr)

ui <- 
  fluidRow(
    actionButton(
      "my_button",
      "Go to next row"
    ),
    dataTableOutput("my_table")
  )

server <- function(input, output){

  values <- reactiveValues()
  values$index <- 1
  values$dat <- iris

  observeEvent(
    input$my_button, {
      values$index <- values$index + 1
    })

  output$my_table <- 
    renderDataTable({
      values$dat %>%
        mutate(row = row_number()) %>%
        datatable() %>% 
        formatStyle(
          "row",
          target = 'row',
          backgroundColor = styleEqual(values$index, c('yellow'))
      )
    }) # somehow highlight the row at the index
}

shinyApp(ui = ui, server = server)

Upvotes: 1

Related Questions