There are basically three ways to incorporate javascript in your Shiny app – choosing one or another basically depends on the amount/reproducibility of code you’ll be using and your javascript expertise.
Runjs shiny how to#
Our general advice would be: when you struggle in doing something with Shiny or it is super inefficient, search for a javascript solution probably the answer is already posted somewhere (yes, using stackoverflow is not shameful for a programmer, you can google a lot with no worries) and all you need to know is how to implement the JS in your Shiny app. (Note that in the gif, it is run in a browser console, but after reading this post you’ll know how to implement the same action in the Shiny app.) Using javascript here is super easy: just define the elements that you’re interested in – the cells of the table – and run the naive loop with the desired condition:
Also if this action should be triggered on some user click, the table would be re-rendered in Shiny and not in JS – we are saving the user’s precious time. Maybe such an option exists in pure Shiny DT somewhere – I did not even bother looking for it, as using JS is so much easier and faster. We would like to modify the standard DT example of styling tables by changing all of the negative values to be red, just to be easier to distinguish them.
Runjs shiny update#
Last but not least – javascript allows you to operate on existing DOM elements while Shiny often re-renders objects (although functions from the update family try their best to avoid it). Omitting the reactivity chain may let you avoid a lot of troubles. What is more it is just faster – especially when some loops are used. Why use javascript in your apps? First of all, it does not limit you as much as pure Shiny – at the end most of the Shiny functions are javascript wrappers with some narrowed functionality. I’m sure that going down the road of Shiny development you will quickly figure out that it is needed on your own. The problem begins when the imagination of the Product Owner or whoever is designing features goes way beyond what Shiny can do 🙂 At Appsilon we recommend using pure javascript heavily in Shiny applications as it is just much more effective and less restricting. That is fine – most of the actions you imagine for your app can be operated via native Shiny code. Many Shiny creators had a data science background, and not a programming background and are not familiar with javascript (including me). Part 2 of a five part series on super solutions for Shiny architecture. Three methods for using javascript code in Shiny applications to build faster apps, avoid unnecessary re-rendering, and add components beyond Shiny’s limits.