pak::pak("posit-dev/shinyreact/pkg-r")ttdviewer is a Shiny app-package for browsing #TidyTuesday datasets. Users pick a dataset title, view the files in List, Summary, and Graphs tabs, and download the data as CSV, parquet, or in its original format. The UI was built with bslib (page_sidebar(), sidebar(), and navset_tab()).
In this post I’ll cover converting the UI to shinyreact, the parts of the conversion the documentation doesn’t cover, and the few surprises I hit along the way.
What is shinyreact?
shinyreact moves the UI out of R. The server still holds the reactive graph (input, reactive(), req(), and bindEvent() all behave as usual), but the page is a React client we write ourselves. The package supplies the plumbing between the two and no UI components.
The R package is version 0.1.0, the documentation calls it pre-release, and it’s not on CRAN:
The R side is small. page_react() replaces the UI function and serves a ui.js (and ui.css) from src_dir, and reactive_output() sends any R value to the client as JSON:
ls("package:shinyreact")
#> [1] "page_bare" "page_react" "page_react_dep" "page_react_html"
#> [5] "reactive_output" "send_message" "wire_tap"On the client, the hooks on window.shinyreact read and write Shiny values: useShinyInput() sets input[[id]], useShinyOutputValue() reads a reactive_output(), and ShinyOutput and ImageOutput host classic Shiny outputs inside React. ShinyModuleProvider namespaces the hook ids, so Shiny modules still work.
The diagram below shows how values move between the two sides:
%%{init: {'theme': 'base', 'themeVariables': { 'fontFamily': 'monospace', "darkMode":false}}}%%
flowchart LR
subgraph Srv["<strong>R server</strong>"]
RO[["<code>reactive_output()</code>"]]
RX[["<code>renderPlot()</code><br><code>renderUI()</code><br><code>downloadHandler()</code>"]]
end
subgraph Cli["<strong>React client</strong>"]
OV("<code>useShinyOutputValue()</code>")
SO("<code>ShinyOutput</code><br><code>ImageOutput</code>")
SI("<code>useShinyInput()</code>")
end
subgraph Inp["<strong>R server</strong>"]
IN[/"<code>input$ds_title</code>"/]
end
RO -->|"i. JSON value"| OV
RX -->|"ii. classic output"| SO
SI -->|"iii. user choice"| IN
style Srv fill:#FFFFFF,color:#000000,stroke:#333,stroke-width:1px,rx:10,ry:10
style Cli fill:#FFFFFF,color:#000000,stroke:#333,stroke-width:1px,rx:10,ry:10
style Inp fill:#FFFFFF,color:#000000,stroke:#333,stroke-width:1px,rx:10,ry:10
style RO fill:#4CBB9D,color:#FFFFFF
style RX fill:#4CBB9D,color:#FFFFFF
style IN fill:#FFFFFF,color:#000000,stroke:#333
style OV fill:#4CBB9D,color:#FFFFFF,rx:5,ry:5
style SO fill:#4CBB9D,color:#FFFFFF,rx:5,ry:5
style SI fill:#4CBB9D,color:#FFFFFF,rx:5,ry:5
Spike first
The documentation only shows R examples for plotly and reactable. It doesn’t mention listviewerlite, renderPlot(), downloadHandler(), or serving the client from an installed R package. Those are four of the app’s five outputs, so before touching the package I built a small prototype (a spike) to test each one with Netflix Titles (one file) and Space Launches (two files).
All four worked.
Lists
listviewerlite::listview() returns HTML, so the server keeps renderUI(), and the client hosts it with the shiny-html-output class:
output$list <- renderUI({
req(data())
listviewerlite::listview(data())
})<ShinyOutput id="list" className="shiny-html-output" />Plots
ImageOutput is only documented for Python, but it follows the same contract as R’s renderPlot(). The client reports its size through .clientdata_output_<id>_width and _height, and draws the image renderPlot() sends back. The inspect_plot() ggplots rendered unchanged:
<ImageOutput id={`plt_${p.value}`} width="100%" height="300px" />Downloads
downloadHandler() binds to an anchor with the shiny-download-link class, so a ShinyOutput with tagName="a" works:
<ShinyOutput
id="download"
tagName="a"
className="btn btn-primary w-100 shiny-download-link"
href=""
target="_blank"
download=""
>
Download Data
</ShinyOutput>The CSV download for Netflix Titles returned 3.0 MB, and the two file zip for Space Launches returned 104 KB.
Packaging
page_react() passes src_dir to page_react_dep(), which builds an htmltools::htmlDependency() with a file source. File sources work from an installed package, so the built client belongs in inst/www/:
app_ui <- function() {
shinyreact::page_react(
useBusyIndicators(spinners = TRUE, pulse = TRUE),
src_dir = system.file("www", package = "ttdviewer"),
theme = bslib::bs_theme(version = 5),
title = "#TidyTuesday Viewer"
)
}bs_theme(version = 5) keeps Bootstrap on the page, so the React components can use the same classes (form-select, nav-tabs, card) the bslib UI used.
The conversion
The client
The client lives in js/, a Vite and TypeScript (TSX) project. npm run build writes inst/www/ui.js and ui.css. React isn’t bundled, because shinyreact.js (served by the R package) already provides it, so Vite maps react to the global shinyreact.React:
rollupOptions: {
external: ["react"],
output: { globals: { react: "shinyreact.React" } },
},js/ is in .Rbuildignore, and the built bundle is committed, so installing the package doesn’t require Node.
The path from source files to the browser looks like this:
%%{init: {'theme': 'base', 'themeVariables': { 'fontFamily': 'monospace', "darkMode":false}}}%%
flowchart TD
Src[("<code>js/src/</code><br>TSX components")]
Build[["<code>npm run build</code><br>(Vite)"]]
WWW[("<code>inst/www/</code><br><code>ui.js</code> + <code>ui.css</code>")]
UI[["<code>app_ui()</code><br><code>page_react()</code>"]]
Br(["Browser"])
Src -->|"i. compile"| Build
Build -->|"ii. write bundle"| WWW
WWW -->|"iii. installed with<br>the package"| UI
UI -->|"iv. serve"| Br
style Src fill:#FFFFFF,color:#000000,stroke:#333
style Build fill:#4CBB9D,color:#FFFFFF
style WWW fill:#FFFFFF,color:#000000,stroke:#333
style UI fill:#4CBB9D,color:#FFFFFF
style Br fill:#FFFFFF,color:#000000,stroke:#333
The modules
Every mod_*_ui() function is gone. Each server module keeps its id, and the client wraps the matching component in a ShinyModuleProvider with the same namespace:
<ShinyModuleProvider namespace="input">
<TitleInput />
</ShinyModuleProvider>The namespace strings on the client have to match the module ids in app_server():
%%{init: {'theme': 'base', 'themeVariables': { 'fontFamily': 'monospace', "darkMode":false}}}%%
flowchart LR
subgraph Srv["<strong>app_server()</strong>"]
MI[["<code>mod_input_server('input')</code>"]]
MD[["<code>mod_download_server('download')</code>"]]
ML[["<code>mod_list_server('listviewerlite')</code>"]]
MS[["<code>mod_summary_server('summary')</code>"]]
MP[["<code>mod_plot_server('viz')</code>"]]
end
subgraph Cli["<strong>ui.tsx</strong>"]
CI("<code>TitleInput</code>")
CD("<code>Download</code>")
CL("<code>ListTab</code>")
CS("<code>SummaryTab</code>")
CP("<code>GraphsTab</code>")
end
MI <-.->|"input"| CI
MD <-.->|"download"| CD
ML <-.->|"listviewerlite"| CL
MS <-.->|"summary"| CS
MP <-.->|"viz"| CP
style Srv fill:#FFFFFF,color:#000000,stroke:#333,stroke-width:1px,rx:10,ry:10
style Cli fill:#FFFFFF,color:#000000,stroke:#333,stroke-width:1px,rx:10,ry:10
style MI fill:#4CBB9D,color:#FFFFFF
style MD fill:#4CBB9D,color:#FFFFFF
style ML fill:#4CBB9D,color:#FFFFFF
style MS fill:#4CBB9D,color:#FFFFFF
style MP fill:#4CBB9D,color:#FFFFFF
style CI fill:#4CBB9D,color:#FFFFFF,rx:5,ry:5
style CD fill:#4CBB9D,color:#FFFFFF,rx:5,ry:5
style CL fill:#4CBB9D,color:#FFFFFF,rx:5,ry:5
style CS fill:#4CBB9D,color:#FFFFFF,rx:5,ry:5
style CP fill:#4CBB9D,color:#FFFFFF,rx:5,ry:5
Plain values (the dataset titles, file names, and the Summary file overview) moved to reactive_output(). For example, mod_input_server() used to get its choices from selectInput() in the UI module. Now it sends them:
output$titles <- shinyreact::reactive_output(
unique(all_tt_combined$title)
)And TitleInput.tsx reads the titles and sends the selection back as input$ds_title:
const titles = asArray(useShinyOutputValue<string | string[]>("titles", []));
const [title, setTitle] = useShinyInput("ds_title", "Space Launches");The table below maps each module to its outputs and client component:
| Module | R output | Client |
|---|---|---|
mod_input |
titles (reactive_output()) |
TitleInput.tsx |
mod_download |
download (downloadHandler()) |
Download.tsx |
mod_list |
list (renderUI()) |
ListTab.tsx |
mod_summary |
overview, choices (reactive_output()); stats, vars, table (renderReactable()) |
SummaryTab.tsx |
mod_plot |
datasets (reactive_output()); plt_<type> (renderPlot()) |
GraphsTab.tsx |
mod_plot_server()
The plot module changed the most. The bslib version populated a dataset selectInput() with updateSelectInput(), created renderPlot() calls inside an observer, and built the plot containers with renderUI(). It also piped return(...) into bindEvent(), so the bindEvent() never ran.
The new version creates one renderPlot() per plot type up front, and each one is gated by req():
purrr::walk(PLOT_TYPES, function(plt) {
output[[paste0("plt_", plt)]] <- renderPlot({
req(plt %in% input$plots)
ds <- selected()
tryCatch(
inspect_plot(ttd = ds, plots = plt),
error = function(err) {
plot.new()
text(0.5, 0.5, "Error generating plot", cex = 1.2, col = "red")
}
)
})
})- 1
-
outside
tryCatch()soreq()is not caught as an error
The checkboxes and plot containers now live in GraphsTab.tsx, and PLOT_TYPES has to match in both places.
Surprises
Length one vectors
reactive_output() passes the R value through unchanged, and Shiny serializes it with auto_unbox, so a character vector of length one arrives as a string, not an array.
The spike’s server sent the file names and the TidyTuesday date for the selected title:
output$files <- reactive_output({
if (is.null(input$title)) return(NULL)
d <- data()
list(names = names(d), date = format(attr(d[[1]], "date")))
})And the client joined the names into a single line:
files && h("p", { id: "files" }, "Files: ", files.names.join(", "), " | TidyTuesday date: ", files.date),The spike’s default title was Netflix Titles, which has one file. The app crashed on load, and the browser console showed:
TypeError: files.names.join is not a function
at App (http://localhost:8765/spike-1795198398/ui.js:20:61)
at vf (http://localhost:8765/shinyreact-0.1.1/shinyreact.js:40:47833)
at Yf (http://localhost:8765/shinyreact-0.1.1/shinyreact.js:40:70472)
at Gd (http://localhost:8765/shinyreact-0.1.1/shinyreact.js:40:80765)
at ry (http://localhost:8765/shinyreact-0.1.1/shinyreact.js:40:116187)
at Kr (http://localhost:8765/shinyreact-0.1.1/shinyreact.js:40:115267)
at uc (http://localhost:8765/shinyreact-0.1.1/shinyreact.js:40:115104)
at cy (http://localhost:8765/shinyreact-0.1.1/shinyreact.js:40:111963)
at My (http://localhost:8765/shinyreact-0.1.1/shinyreact.js:40:123483)
at MessagePort.It (http://localhost:8765/shinyreact-0.1.1/shinyreact.js:17:1579)Shiny’s internal toJSON() shows why. One file arrives as a string, and two files arrive as an array:
# one file (Netflix Titles)
shiny:::toJSON(list(names = c("netflix_titles.csv")))
#> {"names":"netflix_titles.csv"}
# two files (Space Launches)
shiny:::toJSON(list(names = c("agencies.csv", "launches.csv")))
#> {"names":["agencies.csv","launches.csv"]}The spike fixed the client line with [].concat(), which turns a string into a one element array and leaves an array alone:
files && h("p", { id: "files" }, "Files: ", [].concat(files.names).join(", "), " | TidyTuesday date: ", files.date),We can also protect the vector on the server with I(), which keeps it an array:
shiny:::toJSON(list(names = I("netflix_titles.csv")))
#> {"names":["netflix_titles.csv"]}Or we can wrap it on the client, so every reactive_output() is covered. In the package, I went with a small client helper:
export function asArray<T>(x: T | T[] | null | undefined): T[] {
if (x === null || x === undefined) return [];
return Array.isArray(x) ? x : [x];
}Outputs that never rendered
app_server() has a dev output (a listview() of the reactive values) in a closed <details> element in the sidebar. In the bslib UI it never rendered. Inside React it does, and listviewerlite::listview() errors on NULL elements (before a title loads). It now drops them with purrr::compact().
No type to search
The title picker is a native <select>, so it lost the type to search behavior selectize gave selectInput(). With 422 titles that’s noticeable, and it’s the main thing I’m still deciding on.
Recap
The server barely changed: the modules kept their ids, downloadHandler(), renderPlot(), renderUI(), and renderReactable() all work inside React, and the busy indicators still show. What changed is where the UI lives (js/ builds into inst/www/), and how plain values get to it (reactive_output()). The test suite went from 178 to 164 tests, because the UI module tests were dropped with the functions they tested.
The conversion is on the shinyreact branch for now. shinyreact is pre-release, so before merging I need the pkgdown GitHub Action to install it from Remotes, and a decision on the title picker.