Adela
Adela

Reputation: 1797

Math expression in dynamically created sliders

I'm trying to include some mathematical expressions into sliders' labels. It works fine when slider is static. However, it doesn't work when sliders are created via renderUI.

Code below works well untill the number of sliders to be created is changed. In such a moment, math mode stops working in all dynamically created sliders. However, math mode still works for static slider and also for other mathematical text.

library(shiny)

ui <- fluidPage(
  titlePanel("Sliders..."),
  withMathJax(),
  mainPanel(
    # Static slider
    sliderInput(inputId = "slider_alpha",
                label = "\\(\\alpha\\) slider",
                min = 0,
                max = 50,
                value = 30),
    # Text with math mode
    uiOutput("text"),
    # Number of sliders
    numericInput(inputId = "number_of_sliders",
                 label = "Number of sliders",
                 min = 1,
                 max = 3,
                 value = 1,
                 step = 1),
    # Dynamically created sliders
    uiOutput("slider")
  ))

server <- function(input, output) {
  output$text <- renderUI({
    HTML("\\(\\alpha + \\beta = \\gamma\\)")
  })

  output$slider <- renderUI({
    num <- input$number_of_sliders
    sliders <- tagList(
      tags$div(style = "display: inline-block; vertical-align: middle;",
               sliderInput("slider_beta", "\\(\\beta\\) slider",
                           value = 5, min = 0, max = 50, step = 1)),
      tags$div(style = "display: inline-block; vertical-align: middle;",
               sliderInput("slider_gamma", "\\(\\gamma\\) slider",
                           value = 10, min = 0, max = 50, step = 1)),
      tags$div(style = "display: inline-block; vertical-align: middle;",
               sliderInput("slider_gamma", "\\(\\delta\\) slider",
                           value = 10, min = 0, max = 50, step = 1))
    )
    sliders[1:num]
  })

}

shinyApp(ui = ui, server = server)

Upvotes: 0

Views: 118

Answers (1)

demarsylvain
demarsylvain

Reputation: 2185

According to the description of withMathJax(), you should call this function each time, and not only at the beginning, cause of the use of uiOutput().

This function adds MathJax to the page and typeset the math expressions (if found) in the content .... It only needs to be called once in an app unless the content is rendered after the page is loaded, e.g. via renderUI, in which case we have to call it explicitly every time we write math expressions to the output.

If you add withMathJax in your first sliderInput() in your server part, it seems to work.

tags$div(style = "display: inline-block; vertical-align: middle;",
         sliderInput("slider_beta", withMathJax("\\(\\beta\\) slider"),
                     value = 5, min = 0, max = 50, step = 1))

enter image description here

Upvotes: 1

Related Questions