Interfacing Shiny with Javascript -Part 1

[This article was first published on R – Enhance Data, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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)