Home > Back-end >  Shiny: add row to an empty data frame from text input
Shiny: add row to an empty data frame from text input

Time:10-25

The behavior I am looking for:

  1. Text input from user

  2. Press enter

  3. Text is added to a reactive dataframe, and text box is reset

My code so far:

library(tidyverse)
library(shinyWidgets)
library(reactable)
library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(searchInput("search"),
                reactableOutput("search_table"))
)

df <- tibble(names = c("Apple"))

server <- function(input, output, session) {
  
  # Store names
  data <- reactiveValues(df = data.frame(names = NULL))
  
  # Search input -> ENTER -> names gets appended to the dataframe
  observeEvent(input$search,
               {
                 data$df %>% 
                   add_row(names = input$search)
                 
                 updateSearchInput(session, "search", value = "")
               })
  
  # A table showing the names
  output$search_table <- renderReactable({
    reactable(data$df)
  })
  
}

shinyApp(ui, server)

This is how it should look at first; empty "reactable" dataframe

First

Then, you would enter text and press ENTER. The result is added to the dataframe.

Second

Any help or guidance is appreciated

CodePudding user response:

Instead of initializing with NULL use names = character(0) to create a column with zero rows. Additionally I added an if to the observeEvent to check whether input$seach != ""

library(tidyverse)
library(shinyWidgets)
library(reactable)
library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(searchInput("search"),
                reactableOutput("search_table"))
)

df <- tibble(names = c("Apple"))

server <- function(input, output, session) {
  data <- reactiveValues(df = data.frame(names = character(0)))
  
  observeEvent(input$search, {
    if (input$search != "") data$df <- data$df %>% add_row(names = input$search)
    updateSearchInput(session, "search", value = "")
  })
  
  output$search_table <- renderReactable({
    reactable(data$df)
  })
  
}

shinyApp(ui, server)
#> 
#> Listening on http://127.0.0.1:6955

And after adding some items we get:

enter image description here

  • Related