Reputation:
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"]
})
}
Upvotes: 0
Views: 1036
Reputation: 84529
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)
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
}
})
Is it what you want?
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)
Upvotes: 3