Shiny - how to reset/ refresh the form? - r

How can I refresh or reset the ui/ form in Shiny?
I have this button in ui.R:
actionButton("resetInput", "Reset inputs")
What should I do in the server.R to reset the form?
observeEvent(input$resetInput, {
// refresh or reset the form
})
I tried this answer, but I get this error:
Warning: Error in library: there is no package called ‘shinyjs’
Does this package really exist?
Any better way of doing it without installing new packages?

You should put
library(shinyjs)
above your server definition, which is missing in the example you are referring to.
So:
library(shinyjs)
library(shiny)
runApp(shinyApp(
ui = fluidPage(
shinyjs::useShinyjs(),
div(
id = "form",
textInput("text", "Text", ""),
selectInput("select", "Select", 1:5),
actionButton("refresh", "Refresh")
)
),
server = function(input, output, session) {
observeEvent(input$refresh, {
shinyjs::reset("form")
})
}
))
I will modify the answer you are referring to to also include the library call. Hope this helps!

Related

Action button in Shiny app updates query in url with input from user

I have this app:
library(shiny)
ui <- fluidPage(
textInput("query_text","Type something:"),
actionButton(inputId='query_button',
label="Search",
icon = icon("th"),
onclick = paste("location.href='http://www.example.com?lookfor=",
input$query_text, "'", sep=""))
)
server <- function(input, output, session) {
}
shinyApp(ui, server)
I'd like to update the url with the action button, so when the user types something (for example: paper), it updates the url like this:
http://www.example.com/?lookfor=paper
Any ideias how to do it? Maybe wrapping it on a observeEvent?
Based on your replies to my comment, what you're looking for is the updateQueryString function.
library(shiny)
ui <- fluidPage(
textInput("query_text", "Type something:"),
actionButton(inputId = 'query_button', label = "Search")
)
server <- function(input, output, session) {
observeEvent(input$query_button, {
updateQueryString(paste0("?lookfor=", input$query_text))
})
}
shinyApp(ui, server)

R Shiny: Prevent cssloader from showing until action button is clicked

I want to show a cssloader spinner while some processing is done. The cssloader must be shown only after an actionButton is clicked, which triggers the processing of data (this step requires some time, simulated by the sys.Sleep() function in the example below). Also, I want it to show everytime this action is triggered by the actionButton, not only the first time.
Here is an example of what I'm trying:
library(shiny)
library(shinycssloaders)
ui <- fluidPage(
titlePanel("CSS loader test"),
sidebarLayout(
sidebarPanel(
selectInput("imageOptions", "Choose an image:", choices = list(option1="RStudio-Logo-Blue-Gradient.png", option2="RStudio-Logo-All-Gray.png")),
actionButton("getImage", "Show image:")
),
mainPanel(
withSpinner(uiOutput("logo"))
)
)
)
server <- function(input, output) {
url<-reactive(
paste0("https://www.rstudio.com/wp-content/uploads/2014/07/", input$imageOptions)
)
observeEvent(input$getImage,{
output$logo<-renderText({
URL<-isolate(url())
print(URL)
Sys.sleep(2)
c('<center><img src="', URL, '"width="50%" height="50%" align="middle"></center>')
})
})
}
# Run the application
shinyApp(ui = ui, server = server)
I bet there are better ways to acomplish what I needed but here is a solution:
library(shiny)
library(shinycssloaders)
ui <- fluidPage(
titlePanel("CSS loader test"),
sidebarLayout(
sidebarPanel(
selectInput("imageOptions", "Choose an image:", choices = list(option1="RStudio-Logo-Blue-Gradient.png", option2="RStudio-Logo-All-Gray.png")),
actionButton("getImage", "Show image:")
),
mainPanel(
withSpinner(uiOutput("logo"))
)
)
)
server <- function(input, output) {
url<-reactive(
paste0("https://www.rstudio.com/wp-content/uploads/2014/07/", input$imageOptions)
)
output$logo<-renderText({
validate(need(input$getImage, "")) #I'm sending an empty string as message.
input$getImage
URL<-isolate(url())
print(URL)
Sys.sleep(2)
c('<center><img src="', URL, '"width="50%" height="50%" align="middle"></center>')
})
}
# Run the application
shinyApp(ui = ui, server = server)
Instead of getting the reactivity with a call to observeEvent the working solution is to use a call to validate(need(input$getImage, "")) inside a render function.

How to capture shinyalert input field as variable

I'm trying to use the relatively new shinyAlert package to see if it offers better results than the sweetalert package but I'm unable to figure out how to get this:
Myvar <- shinyalert input text
from this minimal example.
library(shiny)
library(shinyjs)
library(shinyalert)
ui <- fluidPage(
shinyjs::useShinyjs(),
useShinyalert(),
actionButton("run", "Run", class = "btn-success")
)
server <- function(input, output, session) {
shinyEnv <- environment()
observeEvent(input$run, {
shinyalert('hello', type='input')
})
}
shinyApp(ui = ui, server = server)
My thanks for any help from you geniouses out there.
Here is how you do it:
library(shiny)
library(shinyalert)
ui <- fluidPage(
useShinyalert(),
actionButton("run", "Run", class = "btn-success")
)
server <- function(input, output, session) {
observeEvent(input$run, {
shinyalert('hello', type='input', callbackR = mycallback)
})
mycallback <- function(value) {
cat(value)
}
}
shinyApp(ui = ui, server = server)
It's done using callbacks. You can assign the value to a reactive variable if you'd like.
I had fully documented the package last month and was about to release it, and then my computer crashed before I had a chance to push to github, and lost all progress. I haven't had a chance to work on it again. So sorry that the documentation isn't great yet, the package is still un-released so use at your own risk for now :)
(Notice that you don't need shinyjs for this)
I have no experience with the package shinyalert, but you can achieve what you want with the widely used and well documented modal dialogs from shiny. Maybe you there is a reason for you to stick with shinyalert that I am unaware off, but if not, example code for achieving what you want with modal dialogs:
ui <- fluidPage(
shinyjs::useShinyjs(),
actionButton("run", "Run", class = "btn-success"),
textOutput("output1")
)
server <- function(input, output, session) {
dataModal <- function(failed = FALSE) {
modalDialog(
textInput("input1", "Enter text:",
placeholder = 'Enter text here'
)
)
}
# Show modal when button is clicked.
observeEvent(input$run, {
showModal(dataModal())
})
output$output1 <- renderText({
input$input1
})
}
shinyApp(ui = ui, server = server)
Let me know if this helps!

How to call an App from within an App in Shiny

I have a Shiny apps directory that looks like this:
-- ShinyApps
|
|_ base_app
|_ my_sub_app
And in base_app I have the following code:
# app.R
#-----------
# Server Section
#-----------
server <- function(input, output) { }
#-----------
# UI section
#-----------
ui <- fixedPage(
h1("My head"),
br(),
br(),
fluidRow(
column(6,
wellPanel(
h3("AMAZON"),
hr(),
a("Go", class = "btn btn-primary btn-md",
href = "http://www.amazon.com")
)),
column(6,
wellPanel(
h3("My Sub App"),
hr(),
a("Go", class = "btn btn-primary btn-md")
# What should I do here to include My_SUB_APP
))
)
)
shinyApp(ui = ui, server = server)
Which looks like this:
What I want to do, is when click on Go button under My SubApp panel, it
will launch sub_app() How can I do it?
I don't want to pass URL (e.g. via href)
Okay, after further analysis this is technically possible.
(But a link solution with href is almost certainly better, the issue is that Shiny Server, or RStudio Connect, or whatever product you are using to host the app needs to have the app loaded already in order to access it, so why not just link to where it's hosting it?)
This solution does not have the obvious "load this directory" workflow and involves specifically loading server.R and ui.R files
In order to overwrite the current UI and server, you need to literally overwrite the ui and server.
Overwriting the ui is easy, you just render the entire thing on the server side from the beginning, and then swap the ui when they decide to press the button.
Overwriting the server is a matter of evaluating the server function of the subAPP, (Which may absolutely have namespace collisions, but for a simple app maybe it's possible)
Here's an example of a way to do it.
app.R file:
#-----------
# UI section
#-----------
ui1 <- fixedPage(
h1("My head"),
br(),
br(),
fluidRow(
column(6,
wellPanel(
h3("AMAZON"),
hr(),
a("Go", class = "btn btn-primary btn-md",
href = "http://www.amazon.com")
)),
column(6,
wellPanel(
h3("My Sub App"),
hr(),
a("Go",
# Link button to input$SubApp1
id = 'SubApp1',
class = "btn btn-primary btn-md action-button")
))
)
)
appUI <- parse(file = 'subdir/ui.R')
appServer <- eval(parse(file = 'subdir/server.R'))
#-----------
# Server Section
#-----------
server <- function(input, output, session) {
output[['fullPage']] <- renderUI({
if(!is.null(input$SubApp1) && input$SubApp1 > 0) {
# If they pressed the button once,
# run the appServer function and evaluate the parsed appUI code
appServer(input, output, session)
eval(appUI)
} else {
#
ui1
}
})
}
ui <- uiOutput('fullPage')
shinyApp(ui = ui, server = server)
subdir/ui.R (Example) :
page <-
navbarPage("X-men",id = "navibar",
tabPanel("placeholder"),
tabPanel("Plot",value = "plot"),
selected = "plot"
)
page[[3]][[1]]$children[[1]]$children[[2]]$children[[1]] <-
tags$li(tags$a(
href = 'http://google.com',
icon("home", lib = "glyphicon")
)
)
page
subdir/server.R (Example) :
function(input, output, session) {
}

How to use shinyFiles package within Shiny Modules - Namespace Issue?

I'm having trouble using the "shinyFilesButton()" and "shinyFilesChoose()" functionality within modules in R shiny.
I believe my issue is related to the namespace functions ("ns()") that effectively create new, unique ids within the modules.
Where do I put the ns() call within the shinyFiles functions? How do I handle this issue on the server side?
I've mocked up an example, with code shown below. The app just selects a file and tells you the info on what you selected. Note that currently no ns() calls are used with any shinyFiles functions. (I've tried wrapping the shinyFilesButton()'s id in the ns(), but then it doesn't match with the shinyFileChoose.)
Currently, this app below will show me files, but only in the root directory. I can't delve deeper into other directories. Additionally, the select button will highlight, but nothing will happen when used.
Edit: I've update the code with an attempt at using the namespaces, per suggestions in the comments. I'm using the ns() function in the shinyFilesButton() call (ui side) and nothing in the server side.
Now I can't see any files when using the file chooser.
Any help?
Below is my code for the app.r file:
#App.R
#Demonstrate issues with ShinyFiles and namesspaces in modules
library(shiny)
library(shinyFiles)
source("shinyFiles_module.R")
server <- function(input, output, session) {
#module Way
callModule(sample,
id="testid",
root_dirs=c(root_on_mac="/Users/Ryan/Desktop/"))
}
ui <- fluidPage(
tagList(
h2("Module Way"),
sample_UI(id = "testid",
label = "shiny file test")
)
)
shinyApp(ui = ui, server = server)
And for the module:
#Sample shinyFiles Module
#trying to get File path using ShinyFiles within a Module
library(shiny)
library(shinyFiles)
#Settings UI function:
# Module UI function
sample_UI <- function(id, label = "Shiny file test") {
# Create a namespace function using the provided id
ns <- NS(id)
#begin UI (wrap all input/ouput in ns() call)
tagList(
strong("Selected Location: "), verbatimTextOutput(ns("file_path")),
shinyFilesButton(
id=ns("get_file_path"),
label="Click Here to Select",
title="Select a file",
multiple= FALSE,
buttonType = "default",
class = NULL)
)
}
# Module server function
sample <- function(input,
output,
session,
root_dirs,
id_value) {
shinyFileChoose(input, id="get_file_path", roots=root_dirs, session=session)
output$file_path <- renderPrint({
parseFilePaths(roots=root_dirs, input$get_file_path)
})
}
Change your module to this and your program works:
library(shiny)
library(shinyFiles)
#Settings UI function:
# Module UI function
sample_UI <- function(id, label = "Shiny file test") {
# Create a namespace function using the provided id
ns <- NS(id)
#begin UI (wrap all input/ouput in ns() call)
tagList(
strong("Selected Location: "), verbatimTextOutput(ns("file_path")),
shinyFilesButton(
id=ns("get_file_path"),
label="Click Here to Select",
title="Select a file",
multiple= FALSE,
buttonType = "default",
class = NULL)
)
}
# Module server function
sample <- function(input,
output,
session,
root_dirs) {
ns <- session$ns
shinyFileChoose(input, id=ns("get_file_path"), roots=root_dirs, session=session)
output$file_path <- renderPrint({
parseFilePaths(roots=root_dirs, input$get_file_path)
})
}
I have the same issue and I resolve it by following Carl's suggestion:
use ns() in ui
remove ns() in server
I am using R3.6.1 and it works. In R3.4 it has problem navigate into the subfolders.
library(shiny)
library(shinyFiles)
#Settings UI function:
# Module UI function
sample_UI <- function(id, label = "Shiny file test") {
# Create a namespace function using the provided id
ns <- NS(id)
#begin UI (wrap all input/ouput in ns() call)
tagList(
strong("Selected Location: "), verbatimTextOutput(ns("file_path")),
shinyFilesButton(
id=ns("get_file_path"),
label="Click Here to Select",
title="Select a file",
multiple= FALSE,
buttonType = "default",
class = NULL)
)
}
# Module server function
sample <- function(input,
output,
session,
root_dirs,
id_value) {
shinyFileChoose(input, id="get_file_path", roots=root_dirs, session=session)
output$file_path <- renderPrint({
parseFilePaths(roots=root_dirs, input$get_file_path)
})
}

Resources