In some use cases, it is very useful to be able to observe the hash url of the current shiny session. However, it seems that the session$clientData$url_hash object doesn't update correctly when NavLink() is used.
A workaround it to use session$reload() while observing NavLink.inputId() as well as using sometimes tags$a() instead of NavLink().
Below a minimal example of the issue with the workaround (commented):
library(shiny)
library(reactRouter)
library(bslib)
ui <- HashRouter(
bslib::page(
reactRouter::Link.shinyInput(
inputId = "home",
to = "/",
h3("reactRouter with dynamic routes", class = "m-3"),
style = "text-decoration: none; color: black"
),
Routes(
Route(
path = "/",
element = div(
# tags$a() necessary instead of NavLink.shinyInput()
tags$a(
href = "#/1", # or "#/1/overview"
"Project 1"
),
tags$a(
href = "#/2",
"Project 2"
)
)
),
Route(
path = "/:id/*",
element = div(
NavLink.shinyInput(
inputId = "overview",
to = "overview",
"Overview"
),
NavLink.shinyInput(
inputId = "analysis",
to = "analysis",
"Analysis"
),
Outlet()
),
reactRouter::Route(
path = "overview",
element = uiOutput("uiOverview")
),
reactRouter::Route(
path = "analysis",
element = uiOutput("uiAnalysis")
)
)
)
)
)
server <- function(input, output, session) {
# FIX HERE
# Necessary to update `url_hash` to get "" (homepage), "1/analysis" and "2/analysis"
# observeEvent(c(input$home, input$overview, input$analysis), {
# session$reload()
# })
url_hash <- shiny::reactiveVal(value = NA)
# update reactive values based on url hash
shiny::observe({
current_url_hash <- session$clientData$url_hash
print(current_url_hash)
url_hash(current_url_hash)
})
output$uiOverview <- renderUI({
url_hash()
})
output$uiAnalysis <- renderUI({
url_hash()
})
}
shinyApp(ui, server)
In some use cases, it is very useful to be able to observe the hash url of the current shiny session. However, it seems that the
session$clientData$url_hashobject doesn't update correctly whenNavLink()is used.A workaround it to use
session$reload()while observingNavLink.inputId()as well as using sometimestags$a()instead ofNavLink().Below a minimal example of the issue with the workaround (commented):