Open In App

How Do You Pass Parameters to a Shiny App via URL in R

Last Updated : 14 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Shiny is an R package that makes it easy to build interactive web applications. Sometimes, you might want to pass information to your Shiny app through the URL so that the app can react to or use this information. This can be useful if you want to customize the app based on the URL or share specific views with others. Here we discuss how to pass parameters to a Shiny app via URL.

What Are URL Parameters?

URL parameters are pieces of information added to the end of a web address. They come after a question mark (?) and are usually in the format key=value. For example, in the URL http://example.com?name=John, name is the key, and John is the value.

Now implement stepwise to Pass the Parameters to a Shiny App via URL in R Programming Language.

Step 1: Install and Load the Required Packages

First, we will Install and Load the Required Packages.

R
install.packages("shiny")
library(shiny)

Step 2: Define the UI

Now we will define the ui.

R
# Define UI
ui <- fluidPage(
  titlePanel("Hello Shiny App"),
  textOutput("greeting")
)

Step 3: Define the Server Logic

Create a server function that parses URL parameters using parseQueryString() and session$clientData$url_search , then render the parsed parameter as text in the UI.

R
# Define server logic
server <- function(input, output, session) {
  # Reactive expression to parse query parameters
  queryParameters <- reactive({
    parseQueryString(session$clientData$url_search)
  })

  # Render text based on the 'name' parameter
  output$greeting <- renderText({
    name <- queryParameters()$name
    if (is.null(name) || name == "") {
      "Hello, World!"
    } else {
      paste("Hello,", name)
    }
  })
}

Step 4: Run the Shiny App

Access the Application without URL Parameters and Combine the UI and server components to create the Shiny app and run it.

R
# Run the application 
shinyApp(ui = ui, server = server)

Output:

Screenshot-2024-08-13-224652
Default Output(without parameters)

Access the Application with URL Parameters

Open a web browser and navigate to the URL

http://127.0.0.1:5452/?name=Geeks!!

Output:

Screenshot-2024-08-13-225152
Access with URL Parameters

Conclusion

Passing parameters to a Shiny app via URL allows for dynamic customization and interaction. By following these steps, we can effectively pass and use URL parameters in our Shiny applications.


Next Article
Article Tags :

Similar Reads