Often when I’m using an R package that enables the use of a JavaScript library I find myself wanting to use other JavaScript functions that the library provides and more often than not they are not enabled through the R functions the package provides.

Thankfully gaining access to these functions is as simple as using Dean Attali’s shinyjs package to write our own function calling the desired functions. Leveraging the JQuery syntax makes the process exceptionally painless for those not well versed in JavaScript.

Here is an example when I wanted to be able to reset a tree created with the shinyTree packages, which implements the jsTree JavaScript library:

library("shiny")
library("shinyjs")
library("shinyTree")

jsFun <- "
  shinyjs.resetTree = function(id) {
    // Deselect all of the leaves and nodes
    $('#' + id).jstree(true).deselect_all();

    // Close all of the nodes
    $('#' + id).jstree(true).close_all();
  };
  "

ui <- pageWithSidebar(
    headerPanel("shinyTree with Core jsTree Function"),

    sidebarPanel(
      width = 2
      , actionButton("reset", "Reset Tree")
    ),

    mainPanel(
      useShinyjs()
      , extendShinyjs(text = jsFun)
      , shinyTree("tree", checkbox = TRUE)
    )
  )

server <- function(input, output) {

  observeEvent(input$reset, {
    js$resetTree("tree")
  })

  output$tree <- renderTree({
    list(
        root1 = "123"
      , root2 = list(
          SubListA = list(
              leaf1 = ""
            , leaf2 = ""
            , leaf3 = ""
            )
        , SubListB = structure(
          list(
              leafA = ""
            , leafB = ""
            )
          , stselected = TRUE
          )
      ) #/ root1
    ) #/ list
  }) #/ renderTree

}

shinyApp(ui, server)

nodes and leaves selected before button click

Clicking the button…

all selections cleared and nodes collapse on click