How to make switches exclusive in Shiny?

394 Views Asked by At

In Shiny I would like to have two (pretty)Switches that I can leave:

  • deselected,
  • or selected only one at a time.

The desired behavior would then be that the 1st switch being TRUE automatically sets the value of the 2nd one to FALSE. And vice-versa.

I made an attempt with the following script, but it doesn't work as desired. In fact, I need to click twice on a switch before the value is correctly changed.

library(shiny)
library(shinyWidgets)

# Define UI
ui <- fluidPage(
    
    # Application title
    titlePanel("Update the switch"),
    
    # Pretty switches 
    prettySwitch('one', 'one'),
    prettySwitch('two', 'two')
    
)

# Define server logic
server <- function(input, output) {
    
    observeEvent({input$one == TRUE}, {
        updateCheckboxInput(
            inputId = "two",
            value = F
        )
    })
    
    observeEvent({input$two == TRUE}, {
        updateCheckboxInput(
            inputId = "one",
            value = F
        )
    })
}

# Run the application 
shinyApp(ui = ui, server = server)
1

There are 1 best solutions below

1
On BEST ANSWER

I think the issue is with how you place the observeEvent, just make it dependant on the buttons, don't specify the condition in the first argument, you can do the rest inside the observeEvent itself. Also, a good pointer would be to stick with the full definitions for bool:TRUE and FALSE, try not to abbreviate it as a good practice

library(shiny)
library(shinyWidgets)

# Define UI
ui <- fluidPage(
    
    # Application title
    titlePanel("Update the switch"),
    
    # Pretty switches 
    prettySwitch('one', 'one'),
    prettySwitch('two', 'two')
    
)

# Define server logic
server <- function(input, output,session) {
    
    observeEvent(input$one, {
        if(input$one == TRUE){
            updateCheckboxInput(session,inputId = "two",value = FALSE)
        }
    }, ignoreInit = TRUE)
    
    observeEvent(input$two,{
        if(input$two == TRUE){
            updateCheckboxInput(session,inputId = "one",value = FALSE)
        }
    }, ignoreInit = TRUE)
}

# Run the application 
shinyApp(ui = ui, server = server)

enter image description here