add break line in checkboxGroupInput choices - Shiny

Viewed 156

I want to add a break line in one choice because it is too long. There is a similar question for the label of a button but the solution does not work for me, see the following code

ui <- fluidPage(
  splitLayout(cellWidths = c(170,80,160),
              tagList(uiOutput("example")))
)

server <- function(input, output) {
  choices_vector <- c("choice 1","choice 2",HTML("I want a line break here <br/> since the label is too long"),"choice 4")
  output$example <- renderUI({
    checkboxGroupInput(inputId = "choices_selec",
                       label = "", choices = choices_vector, selected = F)
  })
}

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

I also tried using using paste0 and collapse (see the following code) and changing uiOutput for htmlOutput but the results are the same

server <- function(input, output) {
  choices_vector <- c("choice 1","choice 2",paste0(c("I want a line break here ", "since the label is too long"), collapse = "<p/>"),"choice 4")
  output$example <- renderUI({
    checkboxGroupInput(inputId = "choices_selec",
                       label = "", choices = choices_vector, selected = F)
  })
}

Any help would be appreciated, thanks!

1 Answers

The problem is checkboxGroupInput only accepts strings as choices. There is nothing we can do unless you change the Shiny source code. Try to think out of the box, why do we need to do it at R preprocessing level. We can use js to post-process it on the client-side (browser).

Here's how, do as usual, but just add this very simple js code after the checkbox:

library(shiny)
ui <- fluidPage(
  splitLayout(cellWidths = c(170,80,160),
              tagList(uiOutput("example")))
)

server <- function(input, output) {
  choices_vector <- c("choice 1"="c1","choice 2"="c2", "I want a line break here<br/> since the label is too long"="c3","choice 4"="c4")
  output$example <- renderUI({
    tagList(
      checkboxGroupInput(inputId = "choices_selec",
                         label = "", choices = choices_vector, selected = F),
      tags$script(
        "
        $('#choices_selec .checkbox label span').map(function(choice){
            this.innerHTML = $(this).text();
        });
        "
      )
    )
  })
  
  observe({
    print(input$choices_selec)
  })
}

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

enter image description here

This code will allow you to use any HTML tag as string input. The HTML will be parsed once the check box is rendered.

I also add names to the choice vector, so you will have a better way on the server side to know what choices are selected.

Related