Home > Software design >  Render text in shiny app using htmloutput
Render text in shiny app using htmloutput

Time:12-19

I want to use htmloutput to render text in shiny app. App works if I have just one object selected in the select input ! As soon as input$var has more than one object the result is not as I expected

require(shiny)
runApp(list(ui = pageWithSidebar(
  headerPanel("Test"),
  sidebarPanel(
    selectInput("var", 
                label = "Choose a variable to display",
                choices = c("Text01", "Text02",
                            "Text03", "Text04"),multiple = TRUE,
                selected = "Text01"),
    sliderInput("range", 
                label = "Range of interest:",
                min = 0, max = 100, value = c(0, 100))
  ),
  mainPanel(htmlOutput("text"))
),
server = function(input, output) {
  
  output$text <- renderUI({
    str1 <- paste("You have selected", input$var)
    str2 <- paste("You have chosen a range that goes from",
                  input$range[1], "to", input$range[2])
    HTML(paste(str1, str2, sep = '<br/>'))
    
  })
}
)
)

enter image description here

How do I modify the code to hav output like :

You have selected Text01,Text02
You have chosen a range that goes from 0 to 100.

CodePudding user response:

Just replace the line

str1 <- paste("You have selected", input$var)

with

str1 <- paste("You have selected", paste(input$var, collapse = ", "))

The problem is that paste() returns a vector of strings when input$var has more than 1 element. With collapse you reduce a string vector input$var to a single value.

CodePudding user response:

library(shiny)

runApp(list(ui = pageWithSidebar(
  headerPanel("Test"),
  sidebarPanel(
    
    selectInput("var", 
                label = "Choose a variable to display",
                choices = c("Text01", "Text02",
                            "Text03", "Text04"), multiple = TRUE,
                selected = "Text01"),
    
    sliderInput("range", 
                label = "Range of interest:",
                min = 0, max = 100, value = c(0, 100))
  ),
  mainPanel(htmlOutput("text"))
),
server = function(input, output) {
  
  output$text <- renderUI({
    
    
    str1 <- paste(input$var, collapse = " ")
    str2 <- paste("You have chosen a range that goes from",
                  input$range[1], "to", input$range[2])
    
    
    tagList(
      div("You have selected", str1),
      div(str2))
  })
}
)
)
  • Related