I intend to build a simple router for my shiny application. Here is an example:
library(shiny)
ui <- fluidPage(
uiOutput("landingPage"),
tags$script(HTML(
'$(document.body).on("click", "[navto]",
function (e) {
Shiny.onInputChange("navigateTo", $(e.currentTarget).attr("navto"));
});'
))
)
server <- function(input, output) {
output$landingPage <- renderUI({
print(paste("Landing ", input$navigateTo))
toOut <- pageSplashUI()
return(toOut)
})
}
pageSplashUI <- function() {
tags$a(href="", navto="GotoNavPage-2", "GotoNavPage-2")
}
# Run the application
shinyApp(ui = ui, server = server)
However, the output$landingPage
was refreshed twice with two different input$navigateTo
value after clicking the href link, the first time is the expected " GotoNavPage-2 " while the second time is NULL .
After struggling for some time, I found the issue can be resolved to add data-toggle`="tab" into the href. The only change is as following:
From:
tags$a(href="", navto="GotoNavPage-2", "GotoNavPage-2")
To:
tags$a(href="", `data-toggle`="tab", navto="GotoNavPage-2", "GotoNavPage-2")
Now, the program is running as expected:
I just don't understand why does the change take effect? What's the usage of data-toggle
="tab" ?
What you're seeing is because the page actually refreshes itself every time you click on the link. It's that simple!
This will be obvious if you add a text input to the UI. Enter some text into the input, then click the link, and you'll see that the page gets refreshed.
So this is the sequence of events:
When you add data-toggle="tab"
(or any of the other possible values in bootstrap), the Bootstrap javascript has some hooks that when you click on a link with that special attribute, it ignores it as a link, which is why you don't see this happening then.
You can simply change the href from "" to "#" which will not cause a page refresh
To be fair, it wasn't immediately clear to me that this is happening. First I spent 5 minutes being confused as to why this is happening, until I realized slowly debugged it to notice this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.