Dark Mode Switch

#| standalone: true
#| components: [viewer]
#| viewerHeight: 200

library(shiny)
library(bslib)

ui <- page_fixed(
  input_dark_mode(id = "mode"), 
  textOutput("mode")
)

server <- function(input, output) {

  output$mode <- renderText({
    paste("You are in", input$mode, "mode.")
  })

}

shinyApp(ui = ui, server = server)
library(shiny)
library(bslib)

ui <- page_fixed(
  input_dark_mode(id = "mode"), 
  textOutput("mode")
)

server <- function(input, output) {

  output$mode <- renderText({
    paste("You are in", input$mode, "mode.")
  })

}

shinyApp(ui = ui, server = server)
No matching items

Relevant Functions

No matching items

Details

A dark mode switch input toggles the app between dark and light modes.

To add a dark mode switch to your app:

  1. Add bslib::input_dark_mode() to the UI of your app to create a dark mode switch. Where you call this function will determine where the dark mode switch will appear within the app’s layout.

  2. Optionally, specify the id parameter of bslib::input_dark_mode() to define the identifier of the switch. When id is specified, you can use it to access the current color mode as a reactive value.

  3. By default, the user’s system settings for the preferred color scheme will be used for the initial mode of the app. To force the initial mode, set the mode parameter to "light" or "dark".

The value of an input component is accessible as a reactive value within the server() function. To access the value of a dark mode switch:

  1. Use input$<dark_mode_switch_id> (e.g., input$mode) to access the value of the dark mode switch. The server value of a dark mode switch is a string: either "light" or "dark".

Variations

Dark mode switch in a navbar

To add a dark mode switch to a navbar, use bslib::page_navbar() to create a page with a navbar, and bslib::nav_spacer() to push the dark mode switch to the right. Place the bslib::input_dark_mode() element within a bslib::nav_item() element, to add the switch to the navbar without creating a corresponding panel.

#| standalone: true
#| components: [viewer]
#| viewerHeight: 300

library(shiny)
library(bslib)

ui <- page_navbar(
  nav_spacer(),
  nav_item(input_dark_mode()), 
  title = "Dark mode switch in navbar"
)

server <- function(input, output) {
}

shinyApp(ui = ui, server = server)
library(shiny)
library(bslib)

ui <- page_navbar(
  nav_spacer(),
  nav_item(input_dark_mode()), 
  title = "Dark mode switch in navbar"
)

server <- function(input, output) {
}

shinyApp(ui = ui, server = server)
No matching items