Shiny for Python and JavaScript: How to Add JS Scripts to Your Dashboards


Web developers love JavaScript. And who can blame them, it’s a fantastic do-it-all language for making stunning websites. But what about Shiny and Shiny for Python? As it turns out, you can add JavaScript scripts to your Shiny for Python dashboards without too much trouble. Today you’ll learn how to add JS scripts to Shiny for Python by making a simple app. All it does is ask the user for its name after clicking on a button, and then render the name or display a cancellation message. Truth be told, you can code the same app in Python/R, but we thought this would be a neat example for potential JavaScript usage.

What are out thoughts on Shiny for Python? Take a look at this First Impressions article.

Table of contents:


Shiny for Python and JavaScript: Let’s Code a Basic App

First things first, we need an app. The good news is that it will take less than 10 lines of code to have it up and running. Open any code editor and create an app.py file. The entire UI will have only three elements:

  1. Title – It’s just an h3 element, not really important.
  2. Button – It’ll open a prompt when clicked, but more on that later.
  3. Paragraph – For displaying the content entered by the user. It’s blank by default, and we care only about the id.

The server() function will remain empty this time, as we won’t handle any logic with Python. Here’s the full code snippet for our simple app:

from shiny import App, ui


app_ui = ui.page_fluid(
    ui.h3("Shiny for Python - JavaScript Example"),
    ui.input_action_button(id="btn", label="Click me!"),
    ui.p(id="prompt_text")
)


def server(input, output, session):
    pass


app = App(ui=app_ui, server=server)

Run the following command from the shell to run the app:

shiny run --reload app.py

It will run on localhost:8000 by default: Image 1 - Our basic Shiny for Python appImage 1 - Our basic Shiny for Python app Image 1 – Our basic Shiny for Python app Nothing happens when you click on the button, which is expected. Before we can tie it to some programming logic, we have to discuss serving static files in Shiny.

How to Serve Static Files

Think of static files as an umbrella term for images, CSS files, and scripts. Basically, it’s anything somewhat related to your app that isn’t written in the main file. A common practice is to create a www folder and put everything mentioned inside it. Please create one yourself and make the following modifications to app.py:

  • Import the Path class from the pathlib library.
  • Create a variable www_dir that will store an absolute path to the wwwdirectory.
  • Inside App(), specify an additional parameter static_assets and set it to www_dir.

Here’s the entire modified snippet in case you got lost in the process:

from shiny import App, ui
from pathlib import Path


app_ui = ui.page_fluid(
    ui.h3("Shiny for Python - JavaScript Example"),
    ui.input_action_button(id="btn", label="Click me!"),
    ui.p(id="prompt_text")
)


def server(input, output, session):
    pass


www_dir = Path(__file__).parent / "www"
app = App(ui=app_ui, server=server, static_assets=www_dir)

The app still looks the same, even if you click on the button: Image 2 - Our basic Shiny for Python app (2)Image 2 - Our basic Shiny for Python app (2) Image 2 – Our basic Shiny for Python app (2) We now have the static assets available in the Shiny for Python app, so next, we can finally add a JavaScript file.

How to Add JavaScript Scripts to Shiny for Python Dashboards

Let’s take a short break from Python and focus on JavaScript. Create a script.js file inside the www directory, and inside it declare a runJS() function. This function will be executed when the button is clicked. The function logic is straightforward – It prompts the user to enter its name, which is then displayed in the below paragraph. If the user cancels the prompt, an appropriate message is shown instead:

function runJS() {
    let text;
    let user = prompt("Please enter your name:", "First name");

    if (user == null || user == "") {
        text = "Prompt cancelled by the user.";
    } else {
        text = "Hello " + user + "!"; 
    }

    document.getElementById("prompt_text").innerHTML = text;
}

But how can you now tie the button to the function? Well, it’s a two-step process:

  1. Add script.js to the document’s head.
  2. Add an onclick property to the button and set its value to runJS() – This will run the function when the button is clicked.

If you prefer Python over English, here’s everything you need:

from shiny import App, ui
from pathlib import Path


app_ui = ui.page_fluid(
    ui.tags.head(
        ui.tags.script(src="script.js")
    ),
    ui.h3("Shiny for Python - JavaScript Example"),
    ui.input_action_button(id="btn", label="Click me!", onclick="runJS()"),
    ui.p(id="prompt_text")
)


def server(input, output, session):
    pass


www_dir = Path(__file__).parent / "www"
app = App(ui=app_ui, server=server, static_assets=www_dir)

Refresh the app and click on the button – You’ll see the prompt like the one below: Image 3 - Entering a value in the promptImage 3 - Entering a value in the prompt Image 3 – Entering a value in the prompt As soon as you hit the OK button, the paragraph text gets populated: Image 4 - Shiny for Python app with the populated paragraph textImage 4 - Shiny for Python app with the populated paragraph text Image 4 – Shiny for Python app with the populated paragraph text But what if you cancel the prompt? Click on the button and hit Cancel instead: Image 5 - Paragraph value when the prompt is canceledImage 5 - Paragraph value when the prompt is canceled Image 5 – Paragraph value when the prompt is canceled Long story short, that’s how you can add JavaScript to your Shiny for Python apps. Let’s wrap things up next.


Summary of Shiny for Python and JavaScript

Adding JavaScript to Shiny for Python apps comes with an important prerequisite, and that is creating and linking the static assets directory. That is if the JS file you plan to use is stored locally. If not, simply add a web url to the src parameter. We hope this article has served you as the basis for more advanced JavaScript use cases in Shiny for Python. Let us know in the comment section below what are your thoughts on this integration, and how you plan to use JS in your apps. Also, feel free to continue the discussion on Twitter – @appsilon. We’d love to hear from you.

Take a break from Python – Learn to scrape dynamic websites in R instead!

The post appeared first on appsilon.com/blog/.





Source link

Related Posts

About The Author

Add Comment