Sharma
Sharma

Reputation: 348

R Shiny create menuItem after object is created/button clicked

I'm trying to dynamically generate a menuItem upon the creation of an object or click of a button (Ideally object). I have tried multiple methods and cannot seem to figure out a clean, working solution.

I have a lot of code so below shall include example code:

ui <- fluidPage(
    dashboardPage(
        dashboardHeader(title = "text"),
        dashboardSidebar(
            sidebarMenu(id = 'MenuTabs',
                        menuItem("Tab1", tabName = "tab1", selected = TRUE)
                        # menuItem("Tab1", tabName = "tab2")
            )
        ),
        dashboardBody(
            tabItems(
                tabItem("tab1",
                        actionButton("newplot", "New plot")),
                tabItem("tab2",
                        plotOutput('Plot'))
             )
        )
    )
)


server <- function(input, output, session){

    output$Plot <- renderPlot({
        input$newplot
        cars2 <- cars + rnorm(nrow(cars))
        plot(cars2)
    })

}


shinyApp(ui, server)

Above I have 2 tabs, 1 with a button (shown), and another with a plot (hidden).

Thanks

Upvotes: 1

Views: 875

Answers (1)

Sharma
Sharma

Reputation: 348

I've managed to solve it. Below is the code that will create a menuItem by pressing a button show.

ui <- fluidPage(
    dashboardPage(
        dashboardHeader(title = "text"),
        dashboardSidebar(
            sidebarMenu(id = 'MenuTabs',
                        menuItem("Tab1", tabName = "tab1", selected = TRUE),
                        # menuItem("Tab1", tabName = "tab2")
                        uiOutput('ui')
            )
        ),
        dashboardBody(
            tabItems(
                tabItem("tab1",
                        actionButton("newplot", "New plot"),
                        actionButton("show", "Show")),
                tabItem("tab2",
                        plotOutput('Plot'))
             )
        )
    )
)


server <- function(input, output, session){

    output$Plot <- renderPlot({
        input$newplot
        # Add a little noise to the cars data
        cars2 <- cars + rnorm(nrow(cars))
        plot(cars2)
    })


    output$ui <- renderUI({
        if(input$show == 0) return()
        print(input$show)
        sidebarMenu(id = 'MenuTabs',
                    menuItem("Tab1", tabName = "tab2")
        )
    })
}


shinyApp(ui, server)

Upvotes: 2

Related Questions