Search code examples
javascriptjqueryshinyshinydashboardshinyjs

ShinyJS toggle applied to shinydashboard box


I'm having issues using shinyjs::toggle.

I have a box displaying selected inputs which I want to show when the user has selected an input and hide when they haven't selected an input.

shinyUI <- function(id) {
checkBoxGroupInput(inputId = "foo",  ......),

div(id=ns("selected_box"),
                    box(
                     width = 24,
                     title = "Selected Foo",
                     textOutput(ns('selected_foo'))))
}

From my understanding, this server code:

shinyjs::toggle(id='selected_box', isTruthy(input$foo)})

Should have an identical effect as this code:

    if(isTruthy(input$foo)) {
      shinyjs::show(id='selected_box', anim = TRUE)
    }
    else {
      shinyjs::hide(id='selected_box', anim = TRUE)
    }
  })

However when I use shinyjs::toggle the selected_box div shows/hides every time the input$foo changes, instead of only when input$foo is empty.


Solution

  • You may want to try conditionalPanel instead

    library(shiny)
    
    ui <- fluidPage(
      checkboxGroupInput('foo', "foo", c('a', 'b', 'c')),
      conditionalPanel(
          'typeof input.foo !== "undefined" && input.foo.length > 0',
          textOutput('text')
      )
    )
    
    server <- function(input, output, session) {
      output$text <- renderText({"abc"})
    }
    
    shinyApp(ui, server)
    

    enter image description here

    Alternatively, if you want to use shinyjs, here is the working code

    library(shiny)
    library(shinyjs)
    ui <- fluidPage(
      useShinyjs(),
      checkboxGroupInput('foo', "foo", c('a', 'b', 'c')),
      textOutput('text')
    )
    
    server <- function(input, output, session) {
      observeEvent(input$foo, {
          print(is.null(input$foo))
          toggle(id='text', condition = !is.null(input$foo))
      }, ignoreNULL = FALSE)
    
      output$text <- renderText({"abc"})
    }
    
    shinyApp(ui, server)
    
    

    The problem you have is you need to specify condition = xx argument, the second positional argument is anim not condition, can't be lazy here. Had this same mistake before xD.