user6883405
user6883405

Reputation: 403

Extracting Elements from Dynamic UI in R Shiny

I have multiple dynamic text elements. The number of elements is determined by a dropdown. I would like to combine each of the dynamic text elements into a list, but am having difficultly.

I have tried creating a separate reactive object to combine the items.

server <-  function(input,output) {

  #define number of names and dynamic names
  output$input_ui1<- renderUI({
    num<- as.integer(input$num)
    lapply(1:num,
           function(i) {
             textInput(inputId = paste0("name",i ),
                       label= paste0("Name",i),
                       value= "enter name")

           })
  })

  #Names into list 
  names_list<-NULL  
  reactive({  
    for (i in 1:input$num ) {
      name<- input[[paste0("name",i)]]
      names_list<-c(names_list, name)
    }
  })


  #access first item of  list of names    
  output$test_text<-reactive({ 
    (names_list[1])  
  })

  #access first name    
  output$test_text2<-reactive({ 
    (input[["name1"]])  
  })



}


ui<- fluidPage(sidebarLayout(
  sidebarPanel(
    selectInput("num","select number of names",choices= seq(1, 10, 1)),
    uiOutput("input_ui1"),
    dateRangeInput("daterange1", "Date range:", start = "2001-01-01", end = "2010-12-31"),
    uiOutput("test_text"),
    uiOutput("test_text2")
  ),
  mainPanel()
))

shinyApp(ui=ui, server=server)

I have two test texts in my UI "test_test" and "test_test2". My expectation is that both should display the same thing, but only the second one is displaying the first name as expected.

Upvotes: 0

Views: 307

Answers (1)

GyD
GyD

Reputation: 4072

Your usage of reactives is not right. For more info see the tutorial.

Original code

#Names into list 
names_list<-NULL  
reactive({  
  for (i in 1:input$num ) {
    name<- input[[paste0("name",i)]]
    names_list<-c(names_list, name)
  }
})

Here is what happens:

  1. You define names_list as NULL
  2. You define a reactive but it is not assigned to any objects, so you can't access it. names_list is just a non-reactive object with the value of NULL.

Also this part is really weird:

#access first item of  list of names    
output$test_text<-reactive({ 
  (names_list[1])  
})

test_text is a uiOutput so you should use renderUI.

Replacement code:

Assign the reactive to names_list, then access it via names_list()

# Names into list 
names_list <- reactive({  
  lapply(1:input$num, function(i) {
    input[[paste0("name",i)]]
  })
})

#access first item of  list of names    
output$test_text <- renderUI( {
  names_list()[[1]]
})

Upvotes: 1

Related Questions