If I use the following UI within Shiny I get roughly the output I want but it isn't actually working as the lowest level navbarMenu displays it's top level label and the arrow to indicate it is expandable but fails to register the sub-items. My guess is because this is designed to be a top-level element only (navbarMenu). My question is, is there another element that will perform the desired task of sub-menus? Being unable to group under a menu item would rapidly become visually inefficient.
shinyUI(navbarPage("My Application",
tabPanel("Component 1"),
tabPanel("Component 2"),
navbarMenu("More",
tabPanel("Sub-Component A"),
tabPanel("Sub-Component B"),
navbarMenu("Yet More",
tabPanel("Subpart 1"),
tabPanel("Subpart 2"))
)
)
)
pretty good question there!
I don't think there is another element you can use, but you can use JavaScript to make it work.
The only change I made to app.R
is including the js file, using:
includeScript("script.js")
. The real part is the script itself: we define 2 eventhandlers:
Clicking on a dropdown
Dropdowns are created by navbarMenu
. They don't have tabPane
connected to them, so all we need is to redefine the default behaviour by toggling the dropdown (open when closed, or close when in an opened state).
Clicking on a tab
There are 3 subtasks to consider when clicking on a tab:
Set active element in tabcontents
We need to show the appropriate tabPane
that was clicked, in order to view the contents. The tabPane
with a class: active
is shown, so first, remove the active
class from every tabPane
, then add active
class for the tab that was clicked.
Set active element in navbar
Same story, the active
tab is visually represented in the navbar
with darker grey color.
Close all dropdowns
After clicking on a specific tab from the navbarMenu
it's probably a good idea to close all dropdowns, otherwise they would remain open.
script.js
$(document).ready(function(){
$('.dropdown').on('click', function(e){
$(this).toggleClass('open');
e.stopPropagation();
e.preventDefault();
});
$('[data-toggle=tab]').on('click', function(e){
let dv = ($(this).attr('data-value'));
//Set active element in tabcontents
$('.tab-pane').removeClass('active');
$('.tab-pane[data-value="' + dv + '"]').addClass('active');
//Set active element in navbar
$('a[data-toggle=tab]').parent().removeClass('active');
$('a[data-value="' + dv + '"]').parent().addClass("active");
//Close the dropdowns
$('.dropdown').removeClass('open');
e.stopPropagation();
e.preventDefault();
});
});
You can quickly try it out with runGist("https://gist.github.com/dgyurko/e1952c5ecbf9a1315b41b8d7ef1f7a8f")
Make sure to test in browser, as it doesn't seem to work properly in the RStudio Viewer!
Demo