A nice RShiny On/Off switch button

Why is the chekboxInput appearance so simple…?

RShiny input controls have a nice design that allows to produce nice web interfaces in a very simple way, but the ‘checkboxInput()’ button is really boring compared to its friends…I was looking for a nice way to present a On/Off (or True/False) switch button in my shiny interfaces but I did not find any, at least not especially designed for Rshiny. Thankfully, there are many examples of switch button on the web, using pure CSS code or using a little javascript. I decided to take one in pure CSS and designed it so that it could be included in Rshiny with a few options.

A simple code for a new function ‘SwitchButton()’

This Rshiny ‘SwitchButton’ function allows to use nice on/off (or True/False) switch buttons instead of the default Rshiny ‘checkboxInput’ function. This only uses CSS code and does not make use of javascript. The ‘switchButton’ function includes two options:

  • Choose between a grey/blue (natural shiny) (col="GB") or a red/green button (col="RG")
  • Choose between TRUE/FALSE (type="TF"), ON/OFF (type="OO") or NULL (type="") button text

Steps to include it are easy:

  • Add CSS script ‘button.css’ in a ‘www’ folder in your Shiny app folder
  • Add R script ‘SwitchButton.R’ in a ‘Rsource’ folder in your Shiny app folder
  • Source the R script in your ‘ui.R’ script, before ‘shinyUI()’ function
  • Use the ‘button.css’ script as the template of your Rshiny interface (or merge it with your own customized css template).
# Code for ui.R
# Source the switch button function
source("./Rsource/SwitchButton.R")

shinyUI(fluidPage(theme = "button.css",
mainPanel(
switchButton(inputId = "Switch.1",
label = "Grey-Blue switch - Default to TRUE - Text TRUE/FALSE",
value = TRUE, col = "GB", type = "TF")
)
))

You may see it in action on my shinyapps repository. You can download the files on my github repository.

comments powered by Disqus