squirrat
squirrat

Reputation: 405

Function to generate dropdown notifications Shiny R

Inside the dashboardHeader, how can you programatically generate dropdown menu items?

dropdownMenu(
  type = "notifications",
  notificationItem(
    text = "message",
    icon = icon("welcome"),
    status = "warning"
  ),
  notificationItem(
    text = "message",
    icon = icon("welcome"),
    status = "warning"
  ),

... #Generate lots more messages

What is the general method in R to generate messages, say from another function that takes in an argument which is the number of messages:

GenerateMessages <- function(number.of.messages) {
#Code to generate messages
}

What would be the code, would it be written in the UI or the Server functions in shiny, dashboard header?

Upvotes: 3

Views: 1631

Answers (1)

squirrat
squirrat

Reputation: 405

I'll answer my own question since it goes beyond the basic dynamic tutorial. I really like this solution because my notifications and logic can go outside of my code, it shortened my app.R by hundreds of lines.

The general form is:

Code inside the UI function:

# Code to create outputs goes in dashboardHeader 
dropdownMenuOutput("messages.type"),
dropdownMenuOutput("notifications.type"),
dropdownMenuOutput("tasks.type")

Code inside Server function:

# Code to generate headers
output$messages.type <- renderMenu(
  dropdownMenu(type = "messages", .list = MessageGenerator())
)
output$notifications.type <- renderMenu(
  dropdownMenu(type = "notifications", .list = NotificationsGenerator())
)
output$tasks.type <- renderMenu(
  dropdownMenu(type = "tasks", .list = TasksGenerator())
)

The main logic is in the MessageGenerator() function. These functions generate a list required to render in the output. The data structure is from a data.frame containing the message information with the proper headers.

This solution scales to generate messages of the three types Messages, Tasks, and Notifications using three functions MessageGenerator(), TasksGenerator(), NotificationsGenerator().

Upvotes: 4

Related Questions