0
votes

I have this Shiny App where a user would write text into a textInput field and whenever the text is in my dataframe the text will be displayed in a tableOutput. The textInput from the user should be then highlighted in a certain color lets say red in the output table. How would i do this?

library(shiny)

df = tibble(Text=c("The quick brown fox", "jumps over", "the lazy dog"))

ui =fluidPage(
    
    fluidRow(
        
        textInput("input", "Textinput"),
        tableOutput("output")
    )
)

server = function(input, output){
    
    df_reactive = reactive({
        df %>%
            filter(str_detect(text, input$input))
    })
    
    output$output = renderTable({
        df_reactive()["text"]
    })
}
1
Don't you want to use the DT package? It has a 'search' feature with highlighting, see this demo. I believe it's the easier solution.Stéphane Laurent
it is definitely easier with DT, but since DT dosnt suit the needs of my whole application, i cannot use ituser12967444

1 Answers

1
votes

enter image description here

library(shiny)
library(tibble)

css <- "
mark {
  padding: 0;
  background-color: white;
  color: red;
}
"

df = tibble(text = c("The quick brown fox", "jumps over", "the lazy dog"))

ui = fluidPage(
  
  tags$head(
    tags$style(HTML(css))
  ),
  
  fluidRow(
    column(
      width = 12,
      textInput("input", "Textinput"),
      tableOutput("output")
    )
  )
  
)

server = function(input, output){
  
  highligthed <- reactive({
    if(input$input != ""){
      gsub(paste0("(", input$input, ")"), "<mark>\\1</mark>", df[["text"]])
    }else{
      df[["text"]]
    }
  })
  
  df_reactive = reactive({
    tibble(text = highligthed())
  })
  
  output$output = renderTable({
    df_reactive()["text"]
  }, sanitize.text = function(x) x)
  
}

shinyApp(ui, server)

Edit

To filter the column, use this code:

  highligthed <- reactive({
    x <- df[["text"]][str_detect(df[["text"]], input$input)]
    if(input$input != ""){
      gsub(paste0("(", input$input, ")"), "<mark>\\1</mark>", x)
    }else{
      x
    }
  })

Old answer (misunderstood the question)

Is it what you want?

enter image description here

library(shiny)
library(tibble)
library(dplyr)
library(stringr)

df = tibble(text = c("The quick brown fox", "jumps over", "the lazy dog"))

ui = fluidPage(
  
  tags$head(
    uiOutput("CSS")
  ),
  
  fluidRow(
    column(
      width = 12,
      textInput("input", "Textinput"),
      tableOutput("output")
    )
  )
  
)

server = function(input, output){
  
  detect <- reactive({
    str_detect(df[["text"]], input$input)
  })
  
  df_reactive = reactive({
    df %>% filter(detect())
  })
  
  output$output = renderTable({
    df_reactive()["text"]
  })
  
  output$CSS = renderUI({
    color <- ifelse(any(detect()), "red", "black")
    css <- sprintf("#input {color: %s;}", color)
    tags$style(HTML(css))
  })
  
}

shinyApp(ui, server)