Interfacing Shiny with Javascript -Part 1

July 26, 2016
By

(This article was first published on R – Enhance Data, and kindly contributed to R-bloggers)

A user customized pop-up

In this first part, we’ll create a custom pop-up generator:

  1. The user enters some text
  2. The user clicks to generate the pop-up
  3. The pop-up pops up !

Creating the files and folders

As usual, you’ll need two files: ui.R and server.R. However, to generate the pop-up we’ll use a js file, let’s create the following in your working directory: www/js/popup.js (just keep popup.js as a blank file, we’ll create our script later).

Communication between Shiny and js

The communication flow is more or less the following:

flow

Creating our UI:

The UI is going to be pretty simple:

  • An input to enter the text to show in the popup
  • An action button to generate the pop-up

Code1.png

You probably noticed the additional line: tags$head(tags$script(src =‘js/popup.js’))

With this line, shiny loads the script and will be able to execute it.

Creating our server.R

Our server is simple too:

  • It needs to notice when the action button is pressed with an observeEvent binded to our button.
  • It will send a message to the JS script to execute it by a using session$sendCustomMessage, its first argument is the message id, the second the argument to be passed to the JS script.

Code2.png

The JS script

The JS script will generate the pop-up. The script is encapsulated in the shiny message handler and will be executed when getting the message from shiny.

You can access the input value you from session$sendCustomMessage by using value.name_of_the_argument.

 Code3.png

You can find the code HERE !

To leave a comment for the author, please follow the link and comment on their blog: R – Enhance Data.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)