In a Shiny app, I would like to be able to use check boxes or radio buttons to toggle on and off the visible output.
Currently, I can achieve this only by creating separate check box ui items and observe conditions for each element I would like to toggle.
library(shiny)
library(shinyjs)
ui <- fluidPage(
useShinyjs(),
uiOutput('select1'),
uiOutput('select2'),
div(id='table1',tableOutput('data1')),
div(id='table2',tableOutput('data2'))
)
server <- function(input, output){
data1 <- data.frame(X1=1:5,
X2=6:10)
data2 <- data.frame(Y1=1:5,
Y2=6:10)
output$data1 <- renderTable(data1)
output$data2 <- renderTable(data2)
output$select1 <- renderUI({
checkboxGroupInput('select1', 'Select T1',
choices = 'table1',
selected = 'table1')
})
output$select2 <- renderUI({
checkboxGroupInput('select2', 'Select T2',
choices = 'table2'
)
})
observe({
toggle(id='table1', condition = input$select1)
})
observe({
toggle(id='table2', condition = input$select2)
})
}
shinyApp(ui, server)
Question 1 When the app loads both tables are displayed despite only one being selected. Toggling the second on and then off is required to hide it. Can this be changed so it isn't displayed on first load?
Question 2
I realise my approach is inefficient and it is likely possible to achieve the same with a single checkBoxGroupInput containing the various options and a single observe condition. I'm really inexperienced here and cannot figure it out.
Your help is appreciated.
CodePudding user response:
toggle
expects a boolean
but input$select
returns a character, which might explain the unexpected behaviour.
With a single checkboxGroupInput
, using %in%
to get booleans:
library(shiny)
library(shinyjs)
ui <- fluidPage(
useShinyjs(),
uiOutput('select'),
div(id='table1',tableOutput('data1')),
div(id='table2',tableOutput('data2'))
)
server <- function(input, output){
data1 <- data.frame(X1=1:5,
X2=6:10)
data2 <- data.frame(Y1=1:5,
Y2=6:10)
output$data1 <- renderTable(data1)
output$data2 <- renderTable(data2)
output$select <- renderUI({
checkboxGroupInput('select', 'Select table',
choices = list('table1','table2'),
selected = 'table1')
})
observe({
toggle(id='table1', condition = "table1" %in% input$select)
toggle(id='table2', condition = "table2" %in% input$select)
})
}
shinyApp(ui, server)