Interfacing Shiny with Javascript -Part 1
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:
- The user enters some text
- The user clicks to generate the pop-up
- 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:
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
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.
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.
You can find the code HERE !
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.