# install.packages(c("shiny", "bslib", "bsicons", "dplyr", "ggplot2", "DT"))bslib: Multi-Page Shiny Apps with Shared Sidebar Controls
Learning goals
By the end of this lesson, you should be able to:
- use
bslibas the main layout system for a Shiny app - create a Shiny app with multiple tabs or pages
- place project-level inputs in one sidebar
- reuse the same sidebar inputs across all tabs
- organize outputs with
card(),layout_columns(), and value boxes
Why bslib?
Base Shiny layouts such as fluidPage(), sidebarLayout(), and tabsetPanel() are still useful, but many modern Shiny apps need more structure:
- a consistent page layout
- multiple views of the same project
- cards that group related outputs
- sidebars that can be opened, closed, and shared across pages
- Bootstrap styling without writing much CSS
The bslib package gives Shiny a more modern layout vocabulary. In this tutorial, we will build a small app where one sidebar controls all tabs.
Packages
Install these packages if needed:
Load the packages:
library(shiny)
library(bslib)
Attaching package: 'bslib'
The following object is masked from 'package:utils':
page
library(dplyr)
Attaching package: 'dplyr'
The following objects are masked from 'package:stats':
filter, lag
The following objects are masked from 'package:base':
intersect, setdiff, setequal, union
library(ggplot2)
library(DT)
Attaching package: 'DT'
The following objects are masked from 'package:shiny':
dataTableOutput, renderDataTable
App idea
We will build a small project dashboard using mtcars.
The app has one project-level sidebar with controls for:
- cylinder groups
- transmission type
- the main numeric metric
- whether to show a trend line
Those inputs are not local to one tab. They apply to every tab:
- the overview tab shows summary values
- the plot tab shows a filtered scatter plot
- the table tab shows the filtered rows
- the notes tab explains the current project state
Prepare the data
The app uses mtcars, but we first create friendlier labels.
cars <- mtcars |>
tibble::rownames_to_column("car") |>
mutate(
cyl = factor(
cyl,
levels = c(4, 6, 8),
labels = c("4 cylinders", "6 cylinders", "8 cylinders")
),
am = factor(
am,
levels = c(0, 1),
labels = c("Automatic", "Manual")
),
gear = factor(gear),
carb = factor(carb)
)
head(cars) car mpg cyl disp hp drat wt qsec vs am
1 Mazda RX4 21.0 6 cylinders 160 110 3.90 2.620 16.46 0 Manual
2 Mazda RX4 Wag 21.0 6 cylinders 160 110 3.90 2.875 17.02 0 Manual
3 Datsun 710 22.8 4 cylinders 108 93 3.85 2.320 18.61 1 Manual
4 Hornet 4 Drive 21.4 6 cylinders 258 110 3.08 3.215 19.44 1 Automatic
5 Hornet Sportabout 18.7 8 cylinders 360 175 3.15 3.440 17.02 0 Automatic
6 Valiant 18.1 6 cylinders 225 105 2.76 3.460 20.22 1 Automatic
gear carb
1 4 4
2 4 4
3 4 1
4 3 1
5 3 2
6 3 1
Step 1: Create the page shell
The outer layout is page_navbar(). Each nav_panel() becomes one page inside the app.
ui_panels_only <- page_navbar(
title = "Motor Trend Explorer",
theme = bs_theme(bootswatch = "flatly"),
nav_panel("Overview"),
nav_panel("Plot"),
nav_panel("Table"),
nav_panel("Notes")
)This gives us pages, but not yet a shared sidebar.
Step 3: Add cards and outputs
bslib::card() is useful for grouping related content. Value boxes are good for high-level numbers. layout_columns() creates responsive columns that adjust as the screen changes.
nav_panel(
"Overview",
layout_columns(
value_box(
title = "Cars",
value = textOutput("n_cars"),
showcase = bsicons::bs_icon("car-front")
),
value_box(
title = "Average metric",
value = textOutput("avg_metric"),
showcase = bsicons::bs_icon("speedometer2")
),
value_box(
title = "Best car",
value = textOutput("best_car"),
showcase = bsicons::bs_icon("trophy")
)
),
card(
card_header("Summary by cylinder group"),
tableOutput("cylinder_summary")
)
)In a real app, each tab can have a different purpose while still using the same project-level filters.
Complete app
Save the following code as app.R, or run it from an R session.
library(shiny)
library(bslib)
library(dplyr)
library(ggplot2)
library(DT)
cars <- mtcars |>
tibble::rownames_to_column("car") |>
mutate(
cyl = factor(
cyl,
levels = c(4, 6, 8),
labels = c("4 cylinders", "6 cylinders", "8 cylinders")
),
am = factor(
am,
levels = c(0, 1),
labels = c("Automatic", "Manual")
),
gear = factor(gear),
carb = factor(carb)
)
metric_choices <- c(
"Miles per gallon" = "mpg",
"Horsepower" = "hp",
"Weight" = "wt",
"Quarter mile time" = "qsec"
)
ui <- page_navbar(
title = "Motor Trend Explorer",
theme = bs_theme(
version = 5,
bootswatch = "flatly",
primary = "#2c7fb8"
),
sidebar = sidebar(
title = "Project controls",
width = 300,
checkboxGroupInput(
inputId = "cylinders",
label = "Cylinders",
choices = levels(cars$cyl),
selected = levels(cars$cyl)
),
checkboxGroupInput(
inputId = "transmission",
label = "Transmission",
choices = levels(cars$am),
selected = levels(cars$am)
),
selectInput(
inputId = "metric",
label = "Main metric",
choices = metric_choices,
selected = "mpg"
),
checkboxInput(
inputId = "show_smooth",
label = "Show trend line",
value = TRUE
)
),
nav_panel(
"Overview",
layout_columns(
value_box(
title = "Cars",
value = textOutput("n_cars"),
showcase = bsicons::bs_icon("car-front")
),
value_box(
title = "Average metric",
value = textOutput("avg_metric"),
showcase = bsicons::bs_icon("speedometer2")
),
value_box(
title = "Best car",
value = textOutput("best_car"),
showcase = bsicons::bs_icon("trophy")
)
),
card(
card_header("Summary by cylinder group"),
tableOutput("cylinder_summary")
)
),
nav_panel(
"Plot",
card(
full_screen = TRUE,
card_header(textOutput("plot_title")),
plotOutput("metric_plot", height = 480)
)
),
nav_panel(
"Table",
card(
full_screen = TRUE,
card_header("Filtered cars"),
DTOutput("cars_table")
)
),
nav_panel(
"Notes",
layout_columns(
card(
card_header("Current project state"),
verbatimTextOutput("project_state")
),
card(
card_header("Pattern"),
tags$p(
"The sidebar is attached to page_navbar(), so the controls are ",
"available across all nav panels."
),
tags$p(
"The server creates one filtered reactive dataset and every tab ",
"uses that same reactive object."
)
)
)
)
)
server <- function(input, output, session) {
filtered_cars <- reactive({
req(input$cylinders, input$transmission)
cars |>
filter(
cyl %in% input$cylinders,
am %in% input$transmission
)
})
selected_metric_label <- reactive({
names(metric_choices)[match(input$metric, metric_choices)]
})
output$n_cars <- renderText({
nrow(filtered_cars())
})
output$avg_metric <- renderText({
value <- mean(filtered_cars()[[input$metric]], na.rm = TRUE)
round(value, 1)
})
output$best_car <- renderText({
data <- filtered_cars()
req(nrow(data) > 0)
data$car[which.max(data[[input$metric]])]
})
output$cylinder_summary <- renderTable({
filtered_cars() |>
group_by(cyl) |>
summarise(
cars = n(),
avg_metric = round(mean(.data[[input$metric]], na.rm = TRUE), 1),
avg_mpg = round(mean(mpg, na.rm = TRUE), 1),
.groups = "drop"
)
})
output$plot_title <- renderText({
paste(selected_metric_label(), "by vehicle weight")
})
output$metric_plot <- renderPlot({
p <- ggplot(
filtered_cars(),
aes(x = wt, y = .data[[input$metric]], color = cyl)
) +
geom_point(size = 3, alpha = 0.85) +
labs(
x = "Weight",
y = selected_metric_label(),
color = "Cylinders"
) +
theme_minimal(base_size = 13)
if (isTRUE(input$show_smooth)) {
p <- p + geom_smooth(method = "lm", se = FALSE, linewidth = 0.8)
}
p
})
output$cars_table <- renderDT({
filtered_cars() |>
select(car, cyl, am, mpg, hp, wt, qsec, gear, carb) |>
datatable(
rownames = FALSE,
options = list(pageLength = 10, scrollX = TRUE)
)
})
output$project_state <- renderPrint({
list(
cylinders = input$cylinders,
transmission = input$transmission,
metric = selected_metric_label(),
rows_after_filtering = nrow(filtered_cars())
)
})
}
shinyApp(ui, server)What to notice
The tabs are only views
The tabs do not each define their own filtering logic. They are different views of the same project state:
- overview numbers
- plot
- table
- notes
This makes the app easier to maintain. When the project-level filters change, all tabs update automatically.
Moving a control into one tab
Not every input belongs in the project-level sidebar. A good rule is:
- put inputs in the sidebar when they affect the whole app
- put inputs inside a tab when they only affect that tab
In this app, show_smooth only affects the plot. It does not change the overview values, the table, or the project notes. That makes it a good candidate for moving into the Plot tab.
Add it to the Plot tab
Then add the checkbox to the Plot tab. One simple option is to place it inside the plot card, above the plot output:
nav_panel(
"Plot",
card(
full_screen = TRUE,
card_header(textOutput("plot_title")),
checkboxInput(
inputId = "show_smooth",
label = "Show trend line",
value = TRUE
),
plotOutput("metric_plot", height = 480)
)
)The server code does not need to change. This line still works:
if (isTRUE(input$show_smooth)) {
p <- p + geom_smooth(method = "lm", se = FALSE, linewidth = 0.8)
}The input is in a different place in the UI, but it still has the same inputId. In a regular Shiny app, input IDs belong to the app session, not to a visual container. Moving the input from the sidebar into the Plot tab changes where the user sees it, not how the server reads it.
Why this is better
This version makes the app easier to understand:
- the sidebar controls the whole project state
- the Plot tab owns the plot-only option
- the server still uses the same
input$show_smoothvalue
As apps grow, this distinction helps keep sidebars from becoming a catch-all for every possible option.
Exercise
Extend the app by adding one more project-level control to the sidebar.
Good options:
- minimum horsepower
- gear count
- number of rows shown in the table
- plot color variable
Then update at least two tabs so they respond to the new control.
Key takeaway
Use a bslib page-level sidebar when a set of inputs should control an entire app. Put the shared data logic in one reactive expression, then let each tab focus only on its own view of that shared state.