Home > Back-end >  R Shiny Multi Line Row In Table From Text Input
R Shiny Multi Line Row In Table From Text Input

Time:11-03

I'm looking to have multiple lines of text displayed in a single row of a table.

The text comes from a text area input, meaning you can add multiple lines of text. When displayed in a table it gets reformatted, removing the multiple lines.

MRE:

library(shiny)
library(DT)
library(shinyWidgets)

ui <- fluidPage(
    titlePanel("Multi-line row in Shiny Table"),
        mainPanel(
            # Add Text
            textAreaInput(inputId = "Long_Text", label = "TEXT:", rows = 5, resize = "both"), br(),
            
            actionButton("Add_text", "New Text"), br(),
            
            # Display Text as Table
            DT::dataTableOutput("Text_Table")
        )
)

server <- function(input, output, session) {

    # Generate Reactive Text Data
        Text_DF <- reactiveValues(data = data.frame(Text = character()))
    
    # Add New Text
        observeEvent(input$Add_text, {
            # Combine New Text With Old Text
            Text_DF$data <- rbind(Text_DF$data, data.frame(Text = input$Long_Text))
        })
    
    # Generate Table
        output$Text_Table = renderDataTable({
            Text_DF$data
        }, escape = FALSE)
}

# Run the application 
shinyApp(ui = ui, server = server)

For example, if you type in:

line 1

line 2

line 3

line 4

the entry in the table is:

line 1 line 2 line 3 line 4

I thought that adding escape = FALSE to renderDataTable would solve it but it did not. Is there another table package that would work better? Is it that the column is defined as a character?

CodePudding user response:

Just replace the "/n" character representing a new line in a string by the corresponding html tag to do so. Look at my solution below.

library(shiny)
library(DT)
library(stringr)

ui <- fluidPage(
  titlePanel("Multi-line row in Shiny Table"),
  mainPanel(
    # Add Text
    textAreaInput(inputId = "Long_Text", label = "TEXT:", rows = 5, resize = "both"), br(),
    
    actionButton("Add_text", "New Text"), br(),
    
    # Display Text as Table
    DT::dataTableOutput("Text_Table")
  )
)

server <- function(input, output, session) {
  
  # Generate Reactive Text Data
  Text_DF <- reactiveValues(data = data.frame(Text = character()))
  
  # Add New Text
  observeEvent(input$Add_text, {
    # Combine New Text With Old Text
    Text_DF$data <- rbind(
      Text_DF$data, 
      data.frame(Text = str_replace_all(input$Long_Text, "\n", "<br>")) # Here the hack
      )
  })
  
  # Generate Table
  output$Text_Table = renderDataTable({
    Text_DF$data
  }, escape = FALSE)

}

# Run the application 
shinyApp(ui = ui, server = server)
  • Related