Search code examples
rshinyshinydashboard

How to highlight a word in shinydashboard in R?


I've found some suggestions of how to highlight a word in other contexts but these didn't work for my problem. Here's my code:


data<-data.frame(X=c("This is an example", "This is not"))
wordlist<-c("This","example","not")

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(sidebarMenu(selectInput("stemmedw", label="Find A Word : ",wordlist))
  ),
  dashboardBody("Title", tabPanel("News",uiOutput("news"))) 
)

server <- function(input, output) {
  output$news <- renderUI({
    pos<-unlist(gregexpr(input$stemmedw,data$X,fixed=TRUE))!=-1
    base<-data.frame(X=data[pos,], stringsAsFactors = FALSE)
    m2 <- data.frame(X=data[pos,], stringsAsFactors = FALSE)
    n<-dim(m2)[1]

    a2 <- list()
    for(i in seq_len(n)) {
      a2[[i]] <- valueBox(i,lapply(m2, "[[", i),  width = 100,color="blue")
    }
    tagList(a2)
  })
}


shinyApp(ui = ui, server = server)

I would like to highlight only the selected word in the text in valueBox. Maybe a different background color, bold style and/or a underline. Ths


Solution

  • Here is one way of using bold with HTML, just complete with the htmls tags you want:

    data<-data.frame(X=c("This is an example", "This is not"))
    wordlist<-c("This","example","not")
    
    ui <- dashboardPage(
      dashboardHeader(),
      dashboardSidebar(sidebarMenu(selectInput("stemmedw", label="Find A Word : ",wordlist))
      ),
      dashboardBody("Title", tabPanel("News",uiOutput("news"))) 
    )
    
    server <- function(input, output) {
      output$news <- renderUI({
        pos<-unlist(gregexpr(input$stemmedw,data$X,fixed=TRUE))!=-1
        base<-data.frame(X=data[pos,], stringsAsFactors = FALSE)
        m2 <- data.frame(X=data[pos,], stringsAsFactors = FALSE)
        n<-dim(m2)[1]
    
        a2 <- list()
    
        for(i in seq_len(n)) {
          a2[[i]] <- valueBox(i, HTML(gsub(input$stemmedw, paste0("<b>", input$stemmedw, "</b>"), m2$X[[i]], fixed = TRUE)), width = 100, color = "blue")
        }
        tagList(a2)
      })
    }
    
    
    shinyApp(ui = ui, server = server)