如何在Shiny的navbarPage右侧添加messageItem消息项?
I get it—trying to drop shinydashboard's dropdownMenu into a standard shiny navbarPage doesn't work out of the box because those components are built for different UI structures. The dropdown ends up left-aligned as a tab instead of sitting neatly on the right side of the navbar. Let's fix that with a bit of custom HTML and CSS.
The Problem with Your Original Code
When you wrap dropdownMenu in a tabPanel, shiny treats it as another navigation tab, so it gets placed alongside your "Plot" tab on the left. We need to inject the dropdown directly into the navbar's right-side container instead.
Working Solution Code
Here's a modified version of your app that gets the dropdown menu aligned correctly to the right:
library(shiny) library(shinydashboard) ui <- shinyUI( navbarPage( "Navbar!", tabPanel( "Plot", sidebarLayout( sidebarPanel(), mainPanel() ) ), # Add the dropdown menu to the navbar's right side tags$li( class = "dropdown navbar-nav navbar-right", dropdownMenu( type = "messages", messageItem( from = "Sales Dept", message = "Sales are steady this month." ), messageItem( from = "Support Team", message = "Ticket #123 has been resolved.", icon = icon("life-ring"), time = "1h ago" ) ) ), # Custom CSS to fix alignment and spacing tags$head( singleton( tags$style(HTML(" .navbar-right .dropdown-menu { right: 0; left: auto; } .navbar-nav > .dropdown > a { padding-top: 15px; padding-bottom: 15px; } ")) ) ) ) ) server = function(input, output) { } shinyApp(ui = ui, server = server)
Key Changes Explained
- Wrapping in
tags$li: We place thedropdownMenuinside a list item with the classesdropdown navbar-nav navbar-right—this tells Bootstrap (which shiny uses under the hood) to position the item on the right side of the navbar, just like in shinydashboard. - Custom CSS: The extra styles ensure the dropdown menu opens to the right (instead of left) and matches the navbar's padding so it doesn't look misaligned.
- No
tabPanel: By skipping thetabPanelwrapper, we avoid treating the dropdown as a navigation tab.
How It Looks
Now your message dropdown will sit neatly on the far right of the navbar, just like it does in a shinydashboard app. Clicking it will show your message items with the same styling you expect from shinydashboard.
内容的提问来源于stack exchange,提问作者Greg

