javascriptrshinyflexdashboard

Hide section on condition


I am building a flexdashboard in R shiny with several sections. Some sections should only be shown under certain conditions and stay hidden otherwise. In this example, I would like to hide the valuebox when its value is 0.

Expected result:

value = 0value > 0


EDIT I condensed the example:

---
title: "Test"
output: 
  flexdashboard::flex_dashboard:
    vertical_layout: scroll
runtime: shiny
---


### Valuebox {.value-box}

```{r}
library(flexdashboard)
library(shiny)
value <- reactiveValues(value = sample(c(0,1), 1))
renderValueBox({
      valueBox(value$value)
})

Any help or pointers are much appreciated!


Solution

  • This is quite straightforward to do if you add a JavaScript block. I cannot get your example code to render, so I'll use the Old Faithful example in the Quarto docs which plots a histogram based on an sliderInput.

    If you wanted to hide the plotOutput (with id "distPlot") when the sliderInput (with id "bins") value is 1, add this code block to the Quarto document:

    ```{js}
    $(document).on("shiny:inputchanged", function (event) {
      if (event.name === "bins") {
        event.value === 1
          ? $("#distPlot").css("visibility", "hidden")
          : $("#distPlot").css("visibility", "visible");
      }
    });
    ```
    

    We can use jQuery syntax as shiny depends on it.

    Note: if you don't want to use JS and are open to an additional R package, see this answer which explains how to do so using R's shinyjs package. I haven't tested this with a Quarto document that uses the shiny runtime.